用小根堆(优先队列实现)的方法
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Queue<ListNode> q = new PriorityQueue<>(new Comparator<ListNode>(){
public int compare(ListNode n1,ListNode n2){
return n1.val - n2.val;
}
});
for(ListNode head : lists){
while(head != null){
q.offer(head);
head = head.next;
}
}
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while(q.size() > 0){
ListNode temp = q.poll();
head.next = temp;
head = head.next;
if(q.size() == 0) head.next = null;
}
return dummy.next;
}
}
书森
|