Java solution


  • 0
    G
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    	int[] array = new int[nums1.length + nums2.length];
    	System.arraycopy(nums1, 0, array, 0, nums1.length);
    	System.arraycopy(nums2, 0, array, nums1.length, nums2.length);
    	Arrays.sort(array);
    	int size = array.length;
    	return (size / 2 * 2 == size)? ((float)array[(size / 2) -1] + array[(size / 2)]) / 2 : array[(size - 1) / 2];
    }

  • 0
    C

    '''

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        if(m==0 && n==0)
            return 0.0;
        boolean odd = (m+n)%2 == 0? true:false;
        int mid = (m+n)/2;
        int i = 0, j=0;
        int count = 0;
        int current = 0;
        double left = 0;
        while(i<=m && j<=n){
            if(i==m)
                current = nums2[j++];
            else if(j==n)
                current = nums1[i++];
            else {
                if(nums1[i]<nums2[j]){
                    current = nums1[i++];
                }else
                    current = nums2[j++];
            }
            if(count == mid){
                if(odd){
                    return (left + current)/2;
                } else
                    return (double)current;
            } else if(count == mid-1 && odd){
                left = current;
            }
            count++;
        }
        return 0.0;
    }
    

    '''


Log in to reply
 

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