Skip to content

Commit 6ac02f2

Browse files
committed
3
1 parent df50931 commit 6ac02f2

File tree

1 file changed

+32
-22
lines changed

1 file changed

+32
-22
lines changed

MergekSortedLists/MergekSortedLists.cpp

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,41 @@
99
class Solution {
1010
public:
1111
ListNode *mergeKLists(vector<ListNode *> &lists) {
12-
// Start typing your C/C++ solution below
13-
// DO NOT write int main() function
12+
return merge(lists, 0, lists.size() - 1);
13+
}
14+
ListNode* merge(vector<ListNode*>& lists, int left, int right) {
15+
if (left > right) {
16+
return NULL;
17+
}
18+
if (left == right) {
19+
return lists[left];
20+
}
21+
int mid = (left + right) / 2;
22+
ListNode* l1 = merge(lists, left, mid);
23+
ListNode* l2 = merge(lists, mid + 1, right);
1424

15-
int n = lists.size();
1625
ListNode head(0);
17-
ListNode *node = &head;
18-
19-
//
20-
// Time complexity O(n*K)
21-
// n stands for the max length of the list in lists
22-
//
23-
while (true) {
24-
int minValue = INT_MAX;
25-
int pos = -1;
26-
for (int i = 0; i < n; i++) {
27-
if (lists[i] != NULL && minValue > lists[i]->val) {
28-
pos = i;
29-
minValue = lists[i]->val;
30-
}
26+
ListNode* curr = &head;
27+
while (l1 && l2) {
28+
if (l1->val < l2->val) {
29+
curr->next = l1;
30+
l1 = l1->next;
31+
} else {
32+
curr->next = l2;
33+
l2 = l2->next;
3134
}
32-
if (pos == -1) break;
33-
node->next = lists[pos];
34-
node = node->next;
35-
lists[pos] = lists[pos]->next;
35+
curr = curr->next;
36+
}
37+
while (l1) {
38+
curr->next = l1;
39+
l1 = l1->next;
40+
curr = curr->next;
41+
}
42+
while (l2) {
43+
curr->next = l2;
44+
l2 = l2->next;
45+
curr = curr->next;
3646
}
3747
return head.next;
3848
}
39-
};
49+
};

0 commit comments

Comments
 (0)