23、Merge k Sorted Lists
合併k個排序鏈表
合併k個排序鏈表,並且返回合併後的排序鏈表。嘗試分析和描述其複雜度。樣例
給出3個排序鏈表[2->4->null,null,-1->null],返回 -1->2->4->null
分析:
我的代碼:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty())return NULL;
for(int i=1;i<lists.size();i++)//直接相加
lists[0]=mergeTwoLists(lists[0],lists[i]);
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2)
{//遞歸形式
if(!l1)return l2;
if(!l2)return l1;
if(l1->val>l2->val)
{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
else
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
}
};
經典代碼:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.empty()){
return nullptr;
}
while(lists.size() > 1){//歸併形式,兩兩相加
lists.push_back(mergeTwoLists(lists[0], lists[1]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1 == nullptr){
return l2;
}
if(l2 == nullptr){
return l1;
}
if(l1->val <= l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}