-
Notifications
You must be signed in to change notification settings - Fork 38
/
TLE_solve.cpp
133 lines (133 loc) · 2.39 KB
/
TLE_solve.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
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
#include <stdlib.h>
#include <climits>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {}
};
class Solution {
public:
/**
* [] [[]]
*/
ListNode *mergeKLists(vector<ListNode*> &lists) {
int i = getMin(lists);
if (i < 0)
return nullptr;
ListNode *head = lists[i];
lists[i] = lists[i]->next;
ListNode *p = head;
while ((i = getMin(lists)) != -1) {
p->next = lists[i];
lists[i] = lists[i]->next;
p = p->next;
}
p->next = nullptr;
return head;
}
private:
int getMin(vector<ListNode *> &lists) {
ListNode *minNode = nullptr;
int pos = -1;
bool updated = false;
int i;
for (i = 0; i < lists.size(); ++i) {
if (cmp(minNode, lists[i]) > 0) {
minNode = lists[i];
pos = i;
updated = true;
}
}
if (updated)
return pos;
else
return -1;
}
int cmp(ListNode *p, ListNode *q)
{
if (p == nullptr && q == nullptr)
return 0;
if (p == nullptr)
return 1;
if (q == nullptr)
return -1;
return p->val - q->val;
}
};
int getLength(ListNode *head)
{
int len = 0;
ListNode *p = head;
while (p) {
++len;
p = p->next;
}
return len;
}
void print(ListNode *head)
{
if (head == nullptr) {
printf("NULL\n");
return;
}
struct ListNode *p = head;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
ListNode * mk_list(ListNode **ha, int a[], int n)
{
if (n < 1)
return nullptr;
ListNode *p = new ListNode(a[0]);
*ha = p;
for (int i = 1; i < n; ++i) {
ListNode *q = new ListNode(a[i]);
p->next = q;
p = q;
}
return p;
}
ListNode *mk_list(int a[], int n)
{
if (n < 1)
return nullptr;
ListNode *head = new ListNode(a[0]);
ListNode *p = head;
for (int i = 1; i < n; ++i) {
ListNode *q = new ListNode(a[i]);
p->next = q;
p = q;
}
return head;
}
void free_list(struct ListNode *head)
{
struct ListNode *p = head;
while (p) {
struct ListNode *q = p->next;
delete p;
p = q;
}
}
int main(int argc, char **argv)
{
Solution solution;
int a[] = {1, 10};
int b[] = {2, 11};
int c[] = {0, 12};
vector<ListNode *> lists = {mk_list(a, 2), mk_list(b, 2), mk_list(c, 2)};
//vector<ListNode *> lists;
//vector<ListNode *> lists = {nullptr, nullptr};
ListNode *head = solution.mergeKLists(lists);
print(head);
return 0;
}