题目描述
合并 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
思路:用Heap存储,每个Heap链表存储一个链表。
代码
1.递归实现
/**
* 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;
if (lists.length == 1) return lists[0];
PriorityQueue<ListNode> queue = new PriorityQueue<>(new Comparator<ListNode>(){
public int compare(ListNode p1, ListNode p2){
return p1.val - p2.val;
}
});
for (int i = 0; i < lists.length; i++){
if (lists[i] != null) queue.add(lists[i]);
}
ListNode pre = new ListNode(0);
ListNode cur = pre;
while(!queue.isEmpty()){
ListNode tmp = queue.poll();
cur.next = tmp;
cur = cur.next;
if (tmp.next != null) queue.add(tmp.next);
}
return pre.next;
}
}
}```