Java Solution using Priority Queue


  • 0
    V

    Thanks to @ColinWang, after seeing his method and I rewrite again by myself.

    import java.util.PriorityQueue;

    public class Solution {

    public ListNode mergeKLists(List<ListNode> lists){

    	if(lists == null){
    		return null;
    	}
    	
    	PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    	
    	for(int i = 0; i < lists.size(); i++){
    		ListNode node = lists.get(i);
    		while(node != null){
    			pq.add(node.val);
    			node = node.next;
    		}
    	}
    
    	if(!pq.isEmpty()){
    	ListNode result = new ListNode(pq.poll());
    	
    	//result.val = pq.poll();
    	ListNode m = result;
    	while(!pq.isEmpty()){
    		result.next = new ListNode(pq.poll());
    		result = result.next;
    	}
    		return m;
    	}else{
    	    return null;
    	}
    		
    }	
    

    }


Log in to reply
 

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