Type Here to Get Search Results !

Median of two sorted arrays leetcode solution.

0

 Median of two sorted arrays leetcode solution.

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.
 

Constraints:

nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106


Solution :- 


class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int size1=nums1.length,size2=nums2.length,i=0,j=0,count=0;

        int[] arr=new int[size1+size2];
        while(i<size1 && j<size2){
            if(nums1[i]<=nums2[j]){
                arr[count++]=nums1[i];
                i++;
            }else{
                arr[count++]=nums2[j];
                j++;
            }
        }
        // for remaining elements  in nums1
        if(i!=size1){
            for(int k=i;k<size1;k++){
                arr[count++]=nums1[k];
            }
        }
        // for remaining elements  in nums2
        if(j!=size2){
            for(int k=j;k<size2;k++){
                arr[count++]=nums2[k];
            }
        }
        int n=arr.length;
        double median=n % 2 != 0?arr[n / 2]:(arr[(n - 1) / 2] + arr[n / 2]) / 2.0;
        
        return median;
    }
}


Post a Comment

0 Comments