-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeKsortedLists.java
More file actions
41 lines (33 loc) · 1.1 KB
/
Copy pathmergeKsortedLists.java
File metadata and controls
41 lines (33 loc) · 1.1 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
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue < ListNode > heap = new PriorityQueue < ListNode > (lists.length, new Comparator < ListNode > () {
@Override
public int compare(ListNode l1, ListNode l2) {
return Integer.compare(l1.val, l2.val);
}
});
for(ListNode node:lists)
{
/* while(node!=null)
{heap.add(node);node = node.next;}
This is approach 1 where you just add a list to heap and then take it back.
We are not taking the advantage of list is sorted.
*/
if(node!=null)
heap.add(node);
}
ListNode temp = new ListNode(0);
ListNode head = temp;
while(!heap.isEmpty())
{
temp.next = heap.poll();
temp = temp.next;
if(temp.next!=null)
{
heap.add(temp.next);
}
}
return head.next;
} }
//heaps