4. Median of 2 shorted Array

LeetCode link

Problem statement:

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

My logic:

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {

        int m = nums1.length;
        int n = nums2.length;
        int i = 0, j = 0, k = 0;      // int k = 0 ;
        int[] nums3 = new int[n+m];     //int nums3 = new int[n+m];


        // for(int i=0; i< m ; i++){
        //     for(int j=0; j<n ; j++){
        //         while(nums1[i] != null || nums2[j] != null ){
        //             if (nums1[i] < nums2[j]){ 
        //                 nums3[k] = nums1[i] ;   
        //                 i ++; 
        //                 k++;
        //             }
        //             else {
        //                 nums3[k] = nums2[k] ;   
        //                 k++;

        //             }
        //         }
        //     }

        // }

        // Merge two sorted arrays
        while (i < m && j < n) {
            if (nums1[i] < nums2[j]) {
                nums3[k++] = nums1[i++];
            } else {
                nums3[k++] = nums2[j++];
            }
        }

        while (i < m) {
            nums3[k++] = nums1[i++];
        }

        while (j < n) {
            nums3[k++] = nums2[j++];
        }




        // if( m+n % 2 == 0){ 
        //     int median= nums3[(n+m)/2] + nums3[((n+m)/2)+ 1]/2 ;
        // }
        // else {
        //     int median =nums3[(n+m)/2];
        // }

        // return median;



        // Calculate median
        if ((m + n) % 2 == 0) {
            return (nums3[(m + n) / 2 - 1] + nums3[(m + n) / 2]) / 2.0;
        } else {
            return nums3[(m + n) / 2];
        }
    }
}
0
Subscribe to my newsletter

Read articles from Dibyashree Chakravarty directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dibyashree Chakravarty
Dibyashree Chakravarty