-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSorted.java
More file actions
90 lines (54 loc) · 1.73 KB
/
MergeKSorted.java
File metadata and controls
90 lines (54 loc) · 1.73 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MergeKSorted {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists.size() == 0) return null;
Comparator<ListNode> comparator = new Comparator<ListNode>(){
public int compare(ListNode x, ListNode y)
{
// Assume neither string is null. Real code should
// probably be more robust
if (x.val < y.val)
{
return -1;
}
if (x.val > y.val)
{
return 1;
}
return 0;
}
};
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.size(), comparator);
for(int i =0; i<lists.size(); i++){
ListNode node = lists.get(i);
if(node == null) continue;
queue.add(node);
lists.set(i, node.next);
}
ListNode all;
if (queue.size() == 0) return null;
all = queue.poll();
if(all.next != null) queue.add(all.next);
ListNode current = all;
while(queue.size()!= 0){
current.next = queue.poll();
current = current.next;
if(current.next!= null){
queue.add(current.next);
}
}
return all;
// Start typing your Java solution below
// DO NOT write main() function
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}