Easy Java solution of Median of Two Sorted Arrays


  • 0
    A

    There are two steps
    step 1: Copy the two given arrays to an array(which i named combinedArray) then sort the
    combined array
    step 2: According to law of finding the median,if the array length is even then the sum of two middle values divided by 2 would be the median.That means
    ( Array[ (length/2) -1 ]+Array[length/2] ) / 2.and if the length is odd then the median would be Array[length/2].

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //step 1
        int nums1Length = nums1.length, nums2Length = nums2.length;
        double median = 0d;//initializing the return value
        int[] combinedArray = new int[nums1Length+nums2Length];
        System.arraycopy(nums1,0,combinedArray,0,nums1Length);
        System.arraycopy(nums2,0,combinedArray,nums1Length,nums2Length);
        Arrays.sort(combinedArray);
        //step 2
        int length = combinedArray.length;
        
        if(length%2==0){
            median = (double) (combinedArray[(length/2)-1]+combinedArray[length/2])/2;
        }else{
            median = (double) combinedArray[length/2];
        }
        return median;
    }
    

    }


Log in to reply
 

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