-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23_gp.cpp
142 lines (125 loc) · 3.04 KB
/
23_gp.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//1. brutal force
class Solution
{
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
vector<int> allValues;
ListNode *head = NULL;
ListNode *current = NULL;
for (int i = 0; i < lists.size(); i++)
{
ListNode *tmp = lists[i];
while (tmp != NULL)
{
allValues.push_back(tmp->val);
tmp = tmp->next;
}
}
sort(allValues.begin(), allValues.end());
for (int i = 0; i < allValues.size(); i++)
{
if (current == NULL)
{
head = new ListNode(allValues[i]);
current = head;
}
else
{
current->next = new ListNode(allValues[i]);
current = current->next;
}
}
return head;
}
};
//2. one by one
class Solution
{
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
ListNode *head = NULL;
ListNode *current = NULL;
while (true)
{
int minVal = INT_MAX;
int minIdx = 0;
bool isDone = true;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i] != NULL)
{
if (lists[i]->val < minVal)
{
minVal = lists[i]->val;
minIdx = i;
}
isDone = false;
}
}
if (isDone)
break;
lists[minIdx] = lists[minIdx]->next;
if (head == NULL)
{
head = new ListNode(minVal);
current = head;
}
else
{
current->next = new ListNode(minVal);
current = current->next;
}
}
return head;
}
};
//3. priority queue
class Compare
{
public:
bool operator() (ListNode *lhs, ListNode *rhs) {
// min on top
return lhs->val > rhs->val;
}
};
class Solution
{
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
ListNode *head = new ListNode(0);
ListNode *current = head;
std::priority_queue<ListNode *, std::vector<ListNode *>, Compare> q;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i] != NULL)
{
q.push(lists[i]);
}
}
while (!q.empty())
{
//出队列
current->next = q.top();
q.pop();
current = current->next;
//判断当前链表是否为空,不为空就将新元素入队
ListNode *next = current->next;
if (next != NULL)
{
q.push(next);
}
}
return head->next;
}
};