

java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0){
return null;
}
//设置优先队列
PriorityQueue<ListNode> pq = new PriorityQueue<>(
lists.length,
(a,b) -> a.val - b.val
);
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
//放入每个数组的第一个元素
for(ListNode head : lists){
if(head != null){
pq.offer(head);
}
}
//排序
while(!pq.isEmpty()){
ListNode minNode = pq.poll();
curr.next = minNode;
curr = curr.next;
if(minNode.next != null){
pq.offer(minNode.next);
}
}
return dummy.next;
}
}
单步解析:
java
PriorityQueue<ListNode> pq = new PriorityQueue<>(
lists.length,
(a,b) -> a.val - b.val
);
设置优先队列PriorityQueue,底层是二叉堆,可以保证每次取出的元素是最大或者最小的;第一个参数lists.length为设置初始容量,不写默认是11,如果装不下系统会自动扩容,但是扩容会及其消耗性能。 (a,b) -> a.val - b.val为Lambda表达式,返回值a.val - b.val为负数系统认为a比b小,为小根堆;a比b大为大根堆;相等则一样大。
java
for(ListNode head : lists){
if(head != null){
pq.offer(head);
}
}
这部分代码在将lists元素存入pq中时只将每个数组的第一个元素存入到了pq中去,这样做既节约内存,也节省时间。
java
if(minNode.next != null){
pq.offer(minNode.next);
}
这里加入以第一个为例,在存入进1后,因为还有后续元素,会将4再存入到队列中去,原队列就从原来的1,1,2变成了1,2,4。