-
Notifications
You must be signed in to change notification settings - Fork 0
/
23-merge-k-sorted-lists.cpp
51 lines (46 loc) · 1.33 KB
/
23-merge-k-sorted-lists.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0)
return NULL;
return BinMerge(lists, 0, lists.size()-1);
}
ListNode* BinMerge(vector<ListNode*> lists, int left, int right){
if(left == right)
return lists[right];
if(left+1 == right){
return mergeTwoLists(lists[left], lists[right]);
}
int mid = left + (right-left)/2;
ListNode* x = BinMerge(lists, mid+1, right);
ListNode* y = BinMerge(lists, left, mid);
return mergeTwoLists(x, y);
}
ListNode* mergeTwoLists(ListNode* a, ListNode* b){
ListNode* ans = new ListNode(0);
ListNode* curr = ans;
while(a && b){
if(a->val > b->val){
curr -> next = b;
b = b->next;
}
else {
curr -> next = a;
a = a->next;
}
curr = curr->next;
}
curr -> next = a ? a : b;
return ans->next;
}
};