Easy Java solution of Median of Two Sorted Arrays

  • 0

    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];
        //step 2
        int length = combinedArray.length;
            median = (double) (combinedArray[(length/2)-1]+combinedArray[length/2])/2;
            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.