forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_23.java
33 lines (27 loc) · 969 Bytes
/
_23.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.Comparator;
import java.util.PriorityQueue;
/**Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.*/
public class _23 {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap = new PriorityQueue(new Comparator<ListNode>(){
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
for(ListNode node : lists){
if(node != null) heap.offer(node);
}
ListNode pre = new ListNode(-1);
ListNode temp = pre;
while(!heap.isEmpty()){
ListNode curr = heap.poll();
temp.next = curr;
temp = temp.next;
if(curr.next != null) heap.offer(curr.next);
}
return pre.next;
}
}