/
MergeKSortedLists.java
49 lines (41 loc) · 993 Bytes
/
MergeKSortedLists.java
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
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Analysis:
Use PriorityQueue
Time complexity: n*log(k)
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0)
return null;
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode a, ListNode b) {
return a.val - b.val;
}
});
for(ListNode list : lists) {
if(list != null)
queue.add(list);
}
ListNode head = new ListNode(0);
ListNode p = head;
while(queue.size() > 0) {
ListNode tmp = queue.poll();
p.next = tmp;
//keep adding next node in list
if(tmp.next != null)
queue.add(tmp.next);
p = p.next;
}
return head.next;
}
}