Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
类似于归并2个链表,暴力一点的方法就是,每取出一个list就与以前的list归并返回merge后list,知道所有list merge完成。
但是可惜,这样做会TLE。贴下代码先:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeKLists(vector<ListNode*>& lists) { 12 ListNode * ret = NULL; 13 for(auto * it : lists){ 14 ret = mergeList(ret, it); 15 } 16 return ret; 17 } 18 19 ListNode * mergeList(ListNode * head1, ListNode * head2) 20 { 21 if(!head1) return head2; 22 if(!head2) return head1; 23 ListNode * head = new ListNode(-1); 24 head->next = head1; 25 ListNode * prev = head; 26 ListNode * tmpNode = NULL; 27 while(head1 && head2){ 28 if(head1->val < head2->val){ 29 prev = prev->next; 30 head1 = head1->next; 31 }else{ 32 tmpNode = head2->next; 33 prev->next = head2; 34 head2->next = head1; 35 prev = head2; 36 head2 = tmpNode; 37 } 38 } 39 if(head2){ 40 prev->next = head2; 41 } 42 return head->next; 43 } 44 };
下面是用堆来做的,先建立一个小堆,找到做小元素。将其merge到一个链表里面。如果后面还有元素,再将其放到堆中。代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 static bool Comp(ListNode * l1, ListNode * l2) 12 { 13 if(l1->val < l2->val) 14 return false; 15 return true; 16 } 17 18 ListNode* mergeKLists(vector<ListNode*>& lists) { 19 vector<ListNode *> removeNullList; 20 removeNullList.reserve(lists.size()); 21 for(auto it = lists.begin(); it != lists.end(); ++it){ 22 if(*it != NULL) 23 removeNullList.push_back(*it); 24 } 25 if(removeNullList.size() == 0) return NULL; //首先去除Null节点 26 make_heap(removeNullList.begin(), removeNullList.end(), Comp); 27 ListNode * helper = new ListNode(-1); 28 ListNode * tail = helper; 29 ListNode * minNode = NULL; 30 while(!removeNullList.empty()){ 31 pop_heap(removeNullList.begin(), removeNullList.end(), Comp); 32 minNode = removeNullList[removeNullList.size()-1]; 33 removeNullList.pop_back(); 34 tail->next = minNode; 35 tail = tail->next; 36 if(minNode->next){//如果后面还有list的话,再次入堆 37 removeNullList.push_back(minNode->next); 38 make_heap(removeNullList.begin(), removeNullList.end(), Comp); 39 } 40 } 41 return helper->next; 42 } 43 };
LeetCode OJ:Merge k Sorted Lists(归并k个链表)
原文:http://www.cnblogs.com/-wang-cheng/p/5012670.html