Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
no comment.
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 *getNext(vector<ListNode *> &lists) { 12 ListNode *next = NULL; 13 int min = INT_MAX; 14 int idx = 0; 15 for (int i = 0; i < lists.size(); ++i) { 16 if (lists[i] != NULL && lists[i]->val < min) { 17 min = lists[i]->val; 18 idx = i; 19 next = lists[i]; 20 } 21 } 22 if (lists[idx] != NULL) lists[idx] = lists[idx]->next; 23 return next; 24 } 25 ListNode *mergeKLists(vector<ListNode *> &lists) { 26 if (lists.size() < 1) return NULL; 27 ListNode *res = new ListNode(-1); 28 ListNode *pos = res; 29 while(pos != NULL) { 30 pos->next = getNext(lists); 31 pos = pos->next; 32 } 33 return res->next; 34 } 35 };
现在LeetCode更新的测试样例,上面的算法会超时。可以使用一个堆来优化。
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 struct cmp { 10 bool operator () (ListNode* a, ListNode* b) { 11 return a->val > b->val; 12 } 13 }; 14 15 class Solution { 16 public: 17 ListNode* mergeKLists(vector<ListNode*>& lists) { 18 ListNode dummy(0); 19 ListNode *p = &dummy; 20 priority_queue<ListNode*, vector<ListNode*>, cmp> heap; 21 for (auto &list : lists) { 22 if (list) heap.push(list); 23 } 24 for ( ; !heap.empty(); heap.pop()) { 25 auto u = heap.top(); 26 p->next = u; 27 p = p->next; 28 if (u->next) heap.push(u->next); 29 } 30 return dummy.next; 31 } 32 };