-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge k sort list.cpp
47 lines (36 loc) · 1.07 KB
/
merge k sort list.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
class Solution
{
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.empty())
return NULL;
vector<int> vect;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i] == nullptr)
continue;
vector<int> mtx;
ListNode *temp = lists[i];
while (temp != nullptr)
{
mtx.push_back(temp->val);
temp = temp->next;
}
vect.insert(vect.end(), mtx.begin(), mtx.end());
}
if (vect.empty())
return nullptr;
sort(vect.begin(), vect.end());
ListNode *root = new ListNode(vect[0]);
ListNode *curr = root;
for (int i = 1; i < vect.size(); i++)
{
ListNode *temp = new ListNode(vect[i]);
curr->next = temp;
curr = curr->next;
}
return root;
}
};
// leetcode - 23