[LeetCode]23. 合并K个排序链表(优先队列;分治待做)

时间:2021-08-23 11:02:50

题目

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:

[

  1->4->5,

  1->3->4,

  2->6

]

输出: 1->1->2->3->4->4->5->6

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/merge-k-sorted-lists

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

方法一 优先队列

  • 分别取每个链表的头节点比较,将最小的作为新链表的第一个节点。若这个节点后面还有节点,则将一个节点放入比较的集合。
  • 比较的集合使用优先队列维护(堆实现)。

方法二 分治

todo

代码

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) {
return null;
} PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>() {// 辅助结构:优先队列
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val)
return -1;
if (o1.val > o2.val)
return 1;
return 0;
}
});
ListNode tempHead = new ListNode(-1);// temp.next为结果链表
ListNode pNode = tempHead; // 将所有链表头加入优先队列
for (ListNode listNode : lists) {
if (listNode != null) {
queue.add(listNode);
}
}
// 某节点加入结果链表后,若其后还有节点,则将该节点加入优先队列等待处理
while (!queue.isEmpty()) {
pNode.next = queue.poll();
pNode = pNode.next;
if (pNode.next != null) {
queue.add(pNode.next);
}
}
return tempHead.next;
}
}