23. Merge k Sorted Lists

Hard

Using PriorityQueue to do heap
  1. add the head of each list to heap

  2. poll out top of heap adding to new linked list

  3. add this element's next to heap

  4. until heap is empty

Override comparator and PriorityQueue instance

Comparator<ListNode> comparator = new Comparator<ListNode>(){
    @Override
    public int compare(ListNode node1, ListNode node2){
        if(node1.val>node2.val) return 1;
        else if(node1.val < node2.val) return -1;
        else return 0;
    }
};
          
Queue<ListNode> queue = new PriorityQueue<ListNode>(comparator);

Why using PriorityQueue to implement heap?

Because any element added to PriorityQueue, it will be sorted in O(lgN)O(lg N) automatically in acceding order. Therefore, adding and deleting an element for PriorityQueue is O(lgN)O(lg N) , find the smallest element is O(1)O(1) . So solving this problem takes O(nlgK)O(nlgK)

Last updated

Was this helpful?