My Accepted Java Solution Using PriorityQueue


  • 7
    W
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode(0), cur = dummy;
        if (lists == null || lists.length < 1) {
            return null;
        }
        PriorityQueue<ListNode> minHeap = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
            public int compare(ListNode l1, ListNode l2) {
                return l1.val - l2.val;
            }    
        });
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                minHeap.offer(lists[i]);
            }
        }
        while (!minHeap.isEmpty()) {
            ListNode temp = minHeap.poll();
            cur.next = temp;
            if (temp.next != null) {
                minHeap.offer(temp.next);
            }
            cur = temp;
        }
        return dummy.next;
    }

  • 0
    S

    Good one ! my version of the code does not use a dummy and it got accepted.

    public ListNode mergeKLists2(ListNode[] lists){
    		ListNode curr = null;
    		ListNode head = null;
    		if(lists == null || lists.length<1)
    			return null;
    		PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.length,new Comparator<ListNode>(){
    			public int compare(ListNode l1, ListNode l2){
    				return l1.val - l2.val;
    			}
    		});
    		// Add all the list nodes to the min heap
    		for(int i=0;i<lists.length;++i){
    			if(lists[i] != null){
    				q.offer(lists[i]);
    			}
    		}
    		
    		// append all nodes to head in the sorted order
    		while(!q.isEmpty()){
    			ListNode tmp = q.poll();
    			if(head == null){
    				
    				head = new ListNode(tmp.val);
    				curr = head;
    			} else {
    				ListNode p = new ListNode(tmp.val);
    				p.next = null;
    				curr.next = p;
    				curr = p;
    			}
    			if(tmp.next != null){
    				q.offer(tmp.next);
    			}
    		}
    		return head;
    	}

Log in to reply
 

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