LeetCode 23. 合并K个升序链表
思路
使用队列将每个链表元素放入,每次获取最小的元素加入到链表中
实现代码
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
Queue<ListNode> heap = new PriorityQueue<>(new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
for (ListNode listNode : lists){
if(listNode!=null) heap.offer(listNode);
}
while (!heap.isEmpty()){
ListNode node = heap.poll();
tail = tail.next = node;
if(node.next !=null) heap.offer(node.next);
}
return dummy.next;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步