合併 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
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
/**
* 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;
ListNode dummyHead=new ListNode(0);
ListNode curr=dummyHead;
PriorityQueue<ListNode>pq=new PriorityQueue<>(new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
return o1.val-o2.val;
}
});
for(ListNode list:lists){
if(list==null)continue;
pq.add(list);
}
while(!pq.isEmpty()){
ListNode nextNode=pq.poll();
curr.next=nextNode;
curr=curr.next;
if(nextNode.next!=null)
pq.add(nextNode.next);
}
return dummyHead.next;
}
}