Skip to content

Commit a8edbc1

Browse files
HARD/src/hard/MergeKSortedList.java
1 parent d882581 commit a8edbc1

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

HARD/src/hard/MergeKSortedList.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package hard;
2+
3+
import java.util.Comparator;
4+
import java.util.PriorityQueue;
5+
6+
import classes.ListNode;
7+
8+
/**As discussed with 司德君,王昊,薛博, this is super easy as long as you can think of heap, offer each of the head node into the min-heap.*/
9+
10+
public class MergeKSortedList {
11+
public ListNode mergeKLists(ListNode[] lists) {
12+
PriorityQueue<ListNode> heap = new PriorityQueue(new Comparator<ListNode>(){
13+
@Override
14+
public int compare(ListNode o1, ListNode o2) {
15+
return o1.val - o2.val;
16+
}
17+
});
18+
19+
for(ListNode node : lists){
20+
if(node != null) heap.offer(node);
21+
}
22+
23+
ListNode pre = new ListNode(-1);
24+
ListNode temp = pre;
25+
while(!heap.isEmpty()){
26+
ListNode curr = heap.poll();
27+
temp.next = curr;
28+
temp = temp.next;
29+
if(curr.next != null) heap.offer(curr.next);
30+
}
31+
return pre.next;
32+
}
33+
}

0 commit comments

Comments
 (0)