Skip to content

Latest commit

 

History

History
59 lines (52 loc) · 1.21 KB

0023 合并K个排序链表.md

File metadata and controls

59 lines (52 loc) · 1.21 KB

0023 合并K个排序链表

Question:

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

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        int k=lists.length;
        if(k==0)
            return null;
        PriorityQueue<ListNode> minHeap = new PriorityQueue<ListNode>(k,new Comparator<ListNode>(){ 
            @Override
            public int compare(ListNode i1,ListNode i2){
                return i1.val-i2.val;
            }
        });
        for(int i=0;i<k;i++){
            if(lists[i]!=null)
                minHeap.add(lists[i]);
        }
        ListNode head=new ListNode(-1);
        ListNode cur=head;
        while(!minHeap.isEmpty()){
            ListNode tmp=minHeap.poll();
            if(tmp.next!=null){
                minHeap.add(tmp.next);
            }
            cur.next=tmp;
            cur=cur.next;
        }
        return head.next;
    }
}