Share my java solution


  • 0
    J

    public class Solution {

    public ListNode mergeKLists(ListNode[] lists) {
    	if(lists.length == 0)
    		return null;
    	if(lists.length == 1) 
    		return lists[0];
    	ListNode[] reLists = new ListNode[lists.length / 2];
    	
    	for(int i = 0; i < reLists.length; i++) {
    		reLists[i] = mergeTwoLists(lists[2 * i], lists[2 * i + 1]);
    	}
    	
    	if(lists.length % 2 == 1)
    		reLists[reLists.length - 1] = mergeTwoLists(reLists[reLists.length - 1], lists[lists.length - 1]);
    	
    	return mergeKLists(reLists);
    }
    
    
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    	ListNode returnNode = new ListNode(0), l3 = returnNode;
    	while(l1 != null && l2 != null) {
    		if(l1.val < l2.val) {
    			l3.next = new ListNode(l1.val);
    			l3 = l3.next;
    			l1 = l1.next;
    		} else {
    			l3.next = new ListNode(l2.val);
    			l3 = l3.next;
    			l2 = l2.next;
    		}
    	}
    	
    	l1 = (l1 == null) ? l2 : l1;
    	
    	l3.next = l1;
    	
    	
    	return returnNode.next;
    }
    

    }


Log in to reply
 

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