Precise code with several good example combined in JAVA


  • 0
    H

    A concise JAVA version of previously posted solution in C

    public class Solution {
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
           int len1 = nums1.length, len2 = nums2.length;
           if(len1 > len2)
                return findMedianSortedArrays(nums2, nums1);
           
           return (findKth(nums1, len1, nums2, len2, (len1 + len2 + 1)/2) + findKth(nums1, len1, nums2, len2, (len1 + len2 + 2)/2)) / 2.0    ;
        }
        
        public int findKth(int[] nums1, int len1, int[] nums2, int len2, int k){
            int l = 0, r = len1 + 1, x  = 0;
            while(l <= r){
                x = (l + r)/2;
                if(v(nums1, x + 1) < v(nums2, k - x)) l = x + 1;
                else if(v(nums2, k-x+1) < v(nums1, x)) r = x - 1;
                else return Math.max(v(nums1, x), v(nums2, k-x));     
            }
            return 0;
        }
        
        public int v(int[] nums, int n){
            if(n<=0) return Integer.MIN_VALUE;
            if(n>nums.length) return Integer.MAX_VALUE;
            return nums[n-1];
        }
    }

  • 0

Log in to reply
 

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