-
Notifications
You must be signed in to change notification settings - Fork 0
/
023. Merge k Sorted Lists.cpp
78 lines (74 loc) · 1.83 KB
/
023. 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// Solution 1: O(n^2)
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return NULL;
for (int i = 0, j = 1; j < lists.size(); i++, j++)
lists[j] = mergeTwoLists(lists[i], lists[j]);
return *(lists.end() - 1);
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1 || !l2) return l1 ? l1 : l2;
ListNode head(0);
ListNode* cur = &head;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
}
else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return head.next;
}
};
// Solution 2: O(nlogn)
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto comp = [](int a, int b) { return a > b; };
priority_queue<int, vector<int>, decltype(comp)>pq(comp);
for (auto x : lists)
while (x) pq.push(x->val), x = x->next;
ListNode head(0);
ListNode* cur = &head;
while (!pq.empty()) {
ListNode* node = new ListNode(pq.top());
cur->next = node;
cur = cur->next;
pq.pop();
}
return head.next;
}
};
// Or just store the ListNode* in priority_queue.
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto comp = [](ListNode* a, ListNode* b){ return a->val > b->val;};
priority_queue<ListNode*, vector<ListNode*>, decltype(comp)>pq(comp);
for(auto x: lists)
while(x) pq.push(x), x = x->next;
ListNode head(0);
ListNode* cur = &head;
while(!pq.empty()){
cur->next = pq.top();
cur = cur->next;
pq.top()->next = NULL;
pq.pop();
}
return head.next;
}
};