Leetcode: Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析:
一个很简单的解法是调用k-1次merge two sorted linkedlist,假设每个list长度为n,那么时间复杂度为2n + 3n + .... kn = (k*(k+1)/2-1)n ~ O(n*k^2),超时:
class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { if(lists.size() == 0) return NULL; ListNode *l = lists[0]; for(int i = 1; i < lists.size(); i++){ l = mergeList(l, lists[i]); } return l; } ListNode * mergeList(ListNode *l1, ListNode *l2){ if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *dummy = new ListNode(-1); dummy->next = NULL; for(ListNode *p = dummy; l1 || l2; p = p->next){ int l1v = l1?l1->val:INT_MAX; int l2v = l2?l2->val:INT_MAX; if(l1v <= l2v){ p->next = l1; l1 = l1->next; }else{ p->next = l2; l2 = l2->next; } } return dummy->next; } };
我们可以采用divide-conquer的思想,先将k个linked list合并成k/2个,然后重复上述过程直到只剩一个linked list。复杂度递推公式为T(k)=2T(k/2)+T(nk),求解得时间复杂度为O(nklogk)。 代码如下:
class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { int n = lists.size(); if(n == 0) return NULL; while(n > 1){ int k = (n + 1)/2; for(int i = 0; i < n/2; i++){ lists[i] = mergeTwoLists(lists[i], lists[i+k]); } n = k; } return lists[0]; } ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode *dummy = new ListNode(-1); dummy->next = NULL; for(ListNode *p = dummy; l1 || l2; p = p->next){ int l1v = l1?l1->val:INT_MAX; int l2v = l2?l2->val:INT_MAX; if(l1v <= l2v){ p->next = l1; l1 = l1->next; }else{ p->next = l2; l2 = l2->next; } } return dummy->next; } };
除了上面的divide-conquer方法,我们还可以用一个最小堆来保存前k个最小的数,然后把最小堆顶端的元素插入的结果链表中,同时将该元素从最小堆删除,然后在将该元素的next元素插入最小堆,直至最小堆为空。因为容量为k的最小堆维护复杂度为logk,所以该算法总时间复杂度为nklogk。代码如下:
struct mycomparison{ bool operator()(const ListNode *l,const ListNode *r){ return l->val > r->val; } }; class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { int n = lists.size(); if(n == 0) return NULL; ListNode *dummy = new ListNode(-1); ListNode *p = dummy; priority_queue<ListNode*, vector<ListNode*>, mycomparison> pri_q; for(int i = 0; i < n; i++) if(lists[i]) pri_q.push(lists[i]); while(!pri_q.empty()){ p->next = pri_q.top(); pri_q.pop(); p = p->next; if(p->next) pri_q.push(p->next); } p->next = NULL; return dummy->next; } };