using priorityQ, very short and straightforward


  • 0
    A
        public ListNode mergeKLists(ListNode[] lists) {
            ListNode aux = new ListNode(0), pt = aux;
            PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
            for (int i = 0; i < lists.length; i ++)
                if (lists[i] != null)
                    pq.offer(lists[i]);
            
            while(pq.size() != 0) {
                pt.next = pq.poll();
                pt = pt.next;
                if (pt.next != null)
                    pq.offer(pt.next);
            }
            return aux.next;
        }
    

Log in to reply
 

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