23. 合并K个排序链表
23. Merge k Sorted Lists
题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
LeetCode23. Merge k Sorted Lists困难
示例:
输入:
[
??1->4->5,
??1->3->4,
??2->6
]
输出: 1->1->2->3->4->4->5->6
Java 实现
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
}
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
});
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (ListNode node : lists) {
if (node != null) {
queue.add(node);
}
}
while (!queue.isEmpty()) {
tail.next = queue.poll();
tail = tail.next;
if (tail.next != null) {
queue.add(tail.next);
}
}
return dummy.next;
}
}
相似题目
- 21. 合并两个有序链表 Merge Two Sorted Lists
- 264. 丑数 II Ugly Number II
参考资料
- https://leetcode-cn.com/problems/merge-k-sorted-lists/
- https://leetcode.com/problems/merge-k-sorted-lists/
原文地址:https://www.cnblogs.com/hglibin/p/10960589.html
时间: 2024-10-08 01:45:01