Java divide and conquer


  • 0
    S
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if(lists.length<1) return null;
            return partition(lists,0,lists.length-1);
        }
        
        private ListNode partition(ListNode[] lists, int s, int e) {
            if(s==e) return lists[s];
            int h = (s+e)/2;
            return merge(partition(lists,s,h), partition(lists,h+1,e));
        }
        
        private ListNode merge(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            ListNode result = null;
            if(l1.val < l2.val) {
                result = l1;
                result.next = merge(l1.next, l2);
            } else {
                result = l2;
                result.next = merge(l1, l2.next);
            }
            return result;
        }
    }
    

Log in to reply
 

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