-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKList.java
More file actions
58 lines (47 loc) · 1.64 KB
/
MergeKList.java
File metadata and controls
58 lines (47 loc) · 1.64 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
51
52
53
54
55
56
57
// merge k list
import java.util.HashSet;
public class MergeKList {
public ListNode mergeKLists(ListNode[] lists) {
ListNode[] nodes = new ListNode[lists.length];
HashSet<Integer> indices = new HashSet<Integer>();
for (int i = 0; i < lists.length; i++) {
nodes[i] = lists[i];
if (lists[i] != null)
indices.add(i);
}
// if all lists are null
if (indices.isEmpty())
return null;
// if only one list is not null return that list
if (indices.size() == 1)
return lists[indices.iterator().next()];
ListNode merged = new ListNode();
ListNode current = merged;
while (indices.size() > 1) {
// find min indices
int min = Integer.MAX_VALUE;
int index = -1;
for (Integer i : indices) {
if (nodes[i].val < min) {
min = nodes[i].val;
index = i;
}
}
current.val = nodes[index].val;
nodes[index] = nodes[index].next;
if (nodes[index] == null)
indices.remove(index);
// create a new node at the end of the list
// to update on the next iteration
if (indices.size() > 1){
ListNode next = new ListNode();
current.next = next;
current = next;
}
}
// when we exit the loop only one list has element insit
// if both are at the end
current.next = nodes[indices.iterator().next()];
return merged;
}
}