Merge K Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Analyse: Similiar to merge sort algorithm. Reuse the code in Merge Two Sorted Lists.
Runtime: 408ms.
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 if(lists.size() == 0) return NULL; 13 if(lists.size() == 1) return lists[0]; 14 15 return divide(lists, 0, lists.size() - 1); 16 } 17 ListNode* divide(vector<ListNode*> &lists, int left, int right){ 18 if(left < right){ 19 int m = (left + right) / 2; 20 return merge2lists(divide(lists, left, m), divide(lists, m + 1, right)); 21 } 22 return lists[left]; 23 } 24 ListNode *merge2lists(ListNode *l1, ListNode *l2) { 25 ListNode pre(-1); 26 27 for(ListNode* p = ⪯ l1 || l2; p = p->next){ 28 int val1 = l1 == nullptr ? INT_MAX : l1->val; 29 int val2 = l2 == nullptr ? INT_MAX : l2->val; 30 31 if(val1 > val2){ 32 p->next = l2; 33 l2 = l2->next; 34 } 35 else{ 36 p->next = l1; 37 l1 = l1->next; 38 } 39 } 40 return pre.next; 41 } 42 };