File tree Expand file tree Collapse file tree 1 file changed +32
-22
lines changed Expand file tree Collapse file tree 1 file changed +32
-22
lines changed Original file line number Diff line number Diff line change 9
9
class Solution {
10
10
public:
11
11
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);
14
24
15
- int n = lists.size ();
16
25
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 ;
31
34
}
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 ;
36
46
}
37
47
return head.next ;
38
48
}
39
- };
49
+ };
You can’t perform that action at this time.
0 commit comments