Java Concise and Super easy Priority Queue based solution


  • 0
    M
    public class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if(lists == null || lists.length == 0){return null;}
            
            ListNode fakeHead = new ListNode(-1);
            ListNode head = fakeHead;
            PriorityQueue <ListNode>pq = new PriorityQueue<>((l1,l2) -> (l1.val - l2.val));
            
            // Add all the heads to priority queue
            for(int i= 0 ; i < lists.length ; i++){
                if(lists[i] != null){ pq.offer(lists[i]); }
            }
            
            // Keep on moving forward untill all the lists are exhausted
            while(!pq.isEmpty()){
                ListNode nextNode = pq.remove();
                head.next = nextNode;
                head = head.next;
                if(nextNode.next != null){  pq.offer(nextNode.next); }
            }
            
            return fakeHead.next;
        }
    }
    

Log in to reply
 

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