标签:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
方法一:实现merger2Lists,然后两个两个List Merge,直到最后,不过超时了
class Solution { public: ListNode *merge2Lists(ListNode* r1, ListNode* r2) { if(NULL == r1) return r2; if(NULL == r2) return r1; ListNode dummy(-1); ListNode *p = &dummy; while(r1 && r2) { if(r1->val < r2->val) { p->next = r1; r1 = r1->next; } else { p->next = r2; r2 = r2->next; } p = p->next; } if(r1) p->next = r1; else if(r2) p->next = r2; return dummy.next; } ListNode *mergeKLists(vector<ListNode *> &lists) { ListNode* p = NULL; for(size_t i = 0; i < lists.size(); i++) { p = merge2Lists(p, lists[i]); //printList(p); } return p; } };
方法二:采用分治法 时间O(KlgN)
注意code:
if((end - beg) == 1) { lists[beg] = merge2Lists(lists[beg], lists[end]); lists[end] = NULL; return lists[beg]; }
而不是
if((end - beg) == 1) { return merge2Lists(lists[beg], lists[end]); }
意思就是将两个list合并后,另外一个list要设置成NULL
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *merge2Lists(ListNode* r1, ListNode* r2) { if(NULL == r1) return r2; if(NULL == r2) return r1; ListNode dummy(-1); ListNode *p = &dummy; while(r1 && r2) { if(r1->val < r2->val) { p->next = r1; r1 = r1->next; } else { p->next = r2; r2 = r2->next; } p = p->next; } if(r1) p->next = r1; else if(r2) p->next = r2; return dummy.next; } ListNode *mergeKListsOverTime(vector<ListNode *> &lists) { ListNode* p = NULL; for(size_t i = 0; i < lists.size(); i++) { p = merge2Lists(p, lists[i]); //printList(p); } return p; } ListNode *mergeKLists(vector<ListNode *> &lists, int beg, int end) { #if 0 cout << "beg\t" << beg << endl; cout << "end\t" << end << endl; for(size_t i = 0; i < lists.size(); i++) printList(lists[i]); #endif if(beg == end) return lists[beg]; if((end - beg) == 1) { lists[beg] = merge2Lists(lists[beg], lists[end]); lists[end] = NULL; return lists[beg]; } ListNode* p1 = mergeKLists(lists, beg, (beg+end)/2); ListNode* p2 = mergeKLists(lists, (beg+end)/2, end); return merge2Lists(p1, p2); } ListNode *mergeKLists(vector<ListNode *> &lists) { if(lists.size() == 0) return NULL; return mergeKLists(lists, 0, lists.size()-1); } };
[LeetCode] Merge k Sorted Lists
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4278793.html