给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
解:使用PriorityQueue;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0){
return null;
}
ListNode pre = new ListNode(-1);
ListNode p = pre;
PriorityQueue pq = new PriorityQueue<>((a,b)->(a.val-b.val));
for(ListNode list : lists){
if(list != null)
pq.add(list);
}
while( !pq.isEmpty() ){
ListNode cur = pq.poll();
p.next = cur;
if(cur.next != null){
pq.add(cur.next);
}
p = p.next;
}
return pre.next;
}
}
执行用时:4 ms, 在所有 Java 提交中击败了70.40%的用户
内存消耗:43.4 MB, 在所有 Java 提交中击败了28.55%的用户



