forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergekSortedLists.h
78 lines (71 loc) · 2.04 KB
/
MergekSortedLists.h
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
/*
Author: Annie Kim, [email protected] : King, [email protected]
Date: Apr 6, 2013
Update: Nov 17, 2014
Problem: Merge k Sorted Lists
Difficulty: easy
Source: http://leetcode.com/onlinejudge#question_23
Notes:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution: Find the smallest list-head first using minimum-heap(lgk).
complexity: O(N*KlgK)
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Mycompare {
public:
bool operator()(ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode *, vector<ListNode *>, Mycompare> q;
for (int i = 0; i < lists.size(); ++i)
if (lists[i])
q.push(lists[i]);
ListNode dummy(0), *cur = &dummy;
while (!q.empty()) {
ListNode *node = q.top();
q.pop();
cur = cur->next = node;
if (node->next)
q.push(node->next);
}
return dummy.next;
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode head(0), *cur = &head;
while (l1 && l2)
{
ListNode **min = l1->val < l2->val ? &l1 : &l2;
cur->next = *min;
cur = cur->next;
*min = (*min)->next;
}
if (l1) cur->next = l1;
if (l2) cur->next = l2;
return head.next;
}
ListNode *mergeKLists_2(vector<ListNode *> &lists) {
if(lists.size()==0) return NULL;
int sz = lists.size();
int end = sz - 1;
while (end > 0) {
int begin = 0;
while (begin < end) {
lists[begin] = mergeTwoLists(lists[begin], lists[end]);
++begin;
--end;
}
}
return lists[0];
}
};