-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc23-mergeKSortedList.cpp
More file actions
81 lines (60 loc) · 1.9 KB
/
lc23-mergeKSortedList.cpp
File metadata and controls
81 lines (60 loc) · 1.9 KB
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
79
80
81
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void moveNode(struct ListNode** srcRef, struct ListNode** destRef){
ListNode* tmp = *srcRef;
*srcRef = tmp->next;
tmp->next = *destRef;
*destRef = tmp;
}
void push(struct ListNode** head, int data){
ListNode* newNode = new ListNode(data);
newNode->next = *head;
*head = newNode;
}
struct MyCompare{
bool operator () (pair<int, int> a, pair<int, int> b){
return a.first > b.first;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode dummy(0);
ListNode* output = &dummy;
priority_queue<pair<int, int>, vector<pair<int,int>>, MyCompare> pq;
for (int i =0 ; i < lists.size(); ++i){
if (lists[i] != NULL){
pq.push(make_pair(lists[i]->val,i));
}
//put the list[i], i in a min heap
//extract the top element and splice element in the ith list
}
while (!pq.empty()){
pair<int,int> elem = pq.top(); pq.pop();
int index = elem.second;
moveNode( &lists[index], &(output->next));
output = output->next;
if (lists[index] != NULL) {
pq.push(make_pair(lists[index]->val, index));
}
}
return dummy.next;
}
};