23. 合并K个升序链表
2023年3月1日
23. 合并K个升序链表
题目:
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
leetcode地址:https://leetcode.cn/problems/merge-k-sorted-lists/
solution
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
ListNode virtualNode = new ListNode(-1);
ListNode index = virtualNode;
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, (o1, o2) -> (o1.val - o2.val));
for(ListNode node : lists) {
if (node != null) {
queue.add(node);
}
}
while(!queue.isEmpty()){
ListNode minNode = queue.poll();
index.next = minNode;
index = index.next;
if (minNode.next != null) {
queue.add(minNode.next);
}
}
return virtualNode.next;
}
}
Loading...