-
Notifications
You must be signed in to change notification settings - Fork 6
/
MergeKSortedList.java
74 lines (58 loc) · 1.74 KB
/
MergeKSortedList.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.*;
import java.util.PriorityQueue;
/**
* Created by abc on 31/12/2015.
* Using priorityQueue or concept of heap to solve the problem.
* Just need to implement the comparator
*/
public class MergeKSortedList {
public ListNode mergeKLists(ListNode[] lists) {
if(null == lists || lists.length ==0){
return null;
}
PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
public int compare(ListNode node1 , ListNode node2){
if(node1.val > node2.val){
return 1;
}
if(node1.val == node2.val){
return 0;
}else
return -1;
}
});
//just add the header of each ListNode
for (ListNode node:
lists) {
if(node != null){
heap.add(node);
}
}
ListNode result = new ListNode(0);
ListNode dummy = result;
while(heap.size() > 0){
ListNode np = heap.poll();
dummy.next = np;
//since we have header of each list node previously
//now we will simply get next element of each pop element and add to heap
//automatically it will match with previous
if(np.next != null){
heap.add(np.next);
}
dummy = dummy.next;
}
return result.next;
}
public static void main(String[] args) {
new MergeKSortedList().mergeKLists(null);
}
}
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}