Simple JAVA Solution


  • 0

    ...

    public class Solution {
    ListNode dummy = new ListNode(Integer.MIN_VALUE);
    
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;
        
        return binaryMerge(lists, 0, lists.length-1);
    }
    
    private ListNode binaryMerge(ListNode[] lists, int low, int high) {
        if (low == high) {
            return lists[low];
        }
        
        // Divide and conquer
        int mid = (low+high)>>>1;
        ListNode l1 = binaryMerge(lists, low, mid);
        ListNode l2 = binaryMerge(lists, mid+1, high);
        
        // Merge list
        ListNode begin = dummy;
        while (l1 != null && l2 != null) {
            if (l2.val < l1.val) {
                begin.next = l2;
                l2 = l2.next;
            } else {
                begin.next = l1;
                l1 = l1.next;
            }
            begin = begin.next;
            begin.next = null;
        }
        
        begin.next = l1 != null ? l1 : l2;
        
        return dummy.next;
    }
    

    }
    ...


Log in to reply
 

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