-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
50 lines (41 loc) · 1.15 KB
/
MergeKSortedLists.java
File metadata and controls
50 lines (41 loc) · 1.15 KB
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
package algorithm.lc;
import java.util.ArrayList;
/**
* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*
*/
// O(\sum_{i} n_i) space, O(\sum_{i} n_i) time
public class MergeKSortedLists {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode fakeHead = new ListNode(0);
ListNode cur = fakeHead;
while (true) {
int index = -1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < lists.size(); ++i) { // find the minimum
if (lists.get(i) != null && lists.get(i).val < min) {
min = lists.get(i).val;
index = i;
}
}
if (index == -1) {
return fakeHead.next;
}
// update pointers
cur.next = lists.get(index);
cur = cur.next;
lists.set(index, lists.get(index).next);
}
}
}
}