Simple Java Solution with PriorityQueue


  • 0
    P
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>((a, b) -> a.val - b.val);
        for (ListNode list : lists) if (list != null)pq.offer(list);
        
        ListNode head = new ListNode(0), curr = head;
        
        while (!pq.isEmpty()) {
            ListNode temp = pq.remove();
            curr.next = temp;
            curr = curr.next;
            if (temp.next != null) pq.offer(temp.next);
        }
        return head.next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.