-1

This is the solution by me. getting wrong output while sorted array length is even and testcases are failing.

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m= nums1.length;
        int x=nums2.length;
        int n=m+x;
        int[] Sortedarray= new int[n];
        int i=0;
        int k=0;
        for(int j=0;j<n;j++){
            if(i<m&&k<x){
                if(nums1== null || nums1[i]>nums2[k]){
                    Sortedarray[j]=nums2[k];
                    k++;
                }
                else{
                    Sortedarray[j]=nums1[i];
                    i++;
                    }
            }
        }
        double median=0;
        if(n%2 == 0){
            median= (Sortedarray[n/2]+ Sortedarray[(n/2)-1])/2;
        }
        else{
            median=Math.floor(Sortedarray[n/2]);
        } 
        return median;
}

for better understanding of the given question, please follow the below instructions. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. ex1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.

ex2: 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.

kssai28
  • 1
  • 1

1 Answers1

0

First of all, you need to cast the integers to double before division, otherwise, it will be rounded to int (basically floor) and the result will be incorrect.

Also, the conditions in the for loop are incorrect. The way it works now makes half of the array empty, as the first 2 elemnts get filled in, that means i == m is true, which makes the for loop skip everything, so take a look at that as well.

Ecto
  • 1,125
  • 1
  • 7
  • 13
  • Hi, yes i got your first point and added casting to the division. I couldnt understand your second point about the conditions in for loop. could you be more specific. – kssai28 Oct 30 '20 at 23:50
  • well you have 2 arrays of size 2 and one goes from i = 0 to m and it contains all the smaller elements, so both elements are added first, so after 1st loop i = 1 and then i = 2, that means the condition (i < m && ...) is false, even before any element from 2nd array may be added. – Ecto Oct 31 '20 at 00:45
  • Ya got it. Thanks! I will work on that – kssai28 Oct 31 '20 at 01:01