Java 8 concise solution with Priority Queue


  • 0
    S
        public ListNode mergeKLists(ListNode[] lists) {
            if(lists == null || lists.length == 0) return null;
            
            //populate priority queue with nodes
            Comparator<ListNode> comparator = Comparator.comparing(listNode -> listNode.val);
            Queue<ListNode> pq = new PriorityQueue<>(lists.length, comparator);
            for(int i=0; i<lists.length; i++){
                if(lists[i] != null) pq.offer(lists[i]);
            }
            
            ListNode dummy = new ListNode(0);
            ListNode i = dummy;
            //prepare result by processing priority queue
            while(!pq.isEmpty()){
                ListNode curMin = pq.poll();
                i.next = curMin;
                i = i.next;
                if(curMin.next != null) pq.offer(curMin.next);
            }
            return dummy.next;
        }    
    
    

Log in to reply
 

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