-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeKSortedLists.java
More file actions
33 lines (26 loc) · 840 Bytes
/
MergeKSortedLists.java
File metadata and controls
33 lines (26 loc) · 840 Bytes
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
package Java;
import java.util.PriorityQueue;
public class MergeKSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
int n = lists.length;
if(n == 0) return null;
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(n, (a, b) -> { return a.val - b.val; });
for(int i=0; i < n; i++){
if(lists[i] != null) pq.offer(lists[i]);
}
ListNode dummyHead = new ListNode(0);
ListNode ptr = dummyHead;
while(pq.size() > 0){
ListNode smallest = pq.poll();
if(smallest.next != null) pq.offer(smallest.next);
ptr.next = smallest;
ptr = ptr.next;
}
return dummyHead.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}