-
Notifications
You must be signed in to change notification settings - Fork 0
/
23. Merge k Sorted Lists
125 lines (104 loc) · 2.62 KB
/
23. Merge k Sorted Lists
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
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
*/
/*
Idea:
Divide & Conquer
Merge lists by pairs, put them into new array and recurively call margeKlists on new array :)
1, 2, 3, 4, 5
12, 34, 5
1234, 5
12345
Time complexity : O(N * log(k))
*/
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
ListNode[] paired = new ListNode[lists.length % 2 == 0 ? lists.length / 2 : lists.length / 2 + 1];
int pairedIdx = 0;
for (int i = 0; i < lists.length; i++) {
if (i + 1 < lists.length) {
paired[pairedIdx++] = mergeSortedLinkedLists(lists[i], lists[++i]);
} else {
paired[pairedIdx++] = lists[i];
}
}
if (paired.length == 1) {
return paired[0];
} else if (paired.length == 2) {
return mergeSortedLinkedLists(paired[0], paired[1]);
} else {
return mergeKLists(paired);
}
}
/*
Idea: merge 2 lists (k-1) times.
1, 2, 3, 4, 5
12, 3, 4, 5
123, 4, 5
1234, 5
12345
Time complexity : O(N*k)
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
for (int i = 1; i < lists.length; i++) {
lists[0] = mergeSortedLinkedLists(lists[0], lists[i]);
}
return lists[0];
}
private ListNode mergeSortedLinkedLists(ListNode a, ListNode b) {
if (a == null) return b;
if (b == null) return a;
ListNode merged;
if (a.val < b.val) {
merged = a;
a = a.next;
} else {
merged = b;
b = b.next;
}
ListNode headRef = merged;
while (a != null || b != null) {
if (a != null && b != null) {
if (a.val < b.val) {
merged.next = a;
a = a.next;
} else {
merged.next = b;
b = b.next;
}
} else if (a != null) {
merged.next = a;
a = a.next;
} else if (b != null) {
merged.next = b;
b = b.next;
} else {
return headRef;
}
merged = merged.next;
}
return headRef;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/