- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathLeetcode23.java
27 lines (25 loc) · 761 Bytes
/
Leetcode23.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
/*
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
*/
classSolution {
publicListNodemergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> q=newPriorityQueue<>((a,b)->a.val-b.val);
ListNodecurr=newListNode(0);
ListNodeans=curr;
for(ListNodel:lists){
while(l!=null){
q.offer(l);
l=l.next;
}
}
while(!q.isEmpty()){
curr.next=q.poll();
curr=curr.next;
curr.next=null;
}
returnans.next;
}
}