Java Solution using Merge sort


  • 0
    N

    `
    public double findMedianSortedArrays(int[] num1, int[] num2) {

        double median=0;
        int[] aux=new int[num1.length+num2.length];
    
        
        for(int i=0,j=0,k=0;k<aux.length;){
    
            if(i==num1.length)       aux[k++]=num2[j++];
        
            else if(j==num2.length)  aux[k++]=num1[i++];
    
            else if(num1[i]==num2[j]){
                aux[k++]=num2[j++];
                aux[k++]=num1[i++];
            }
            else if(num1[i]<num2[j])   aux[k++]=num1[i++]; 
            else if(num1[i]>num2[j])   aux[k++]=num2[j++];         
        }
    
        int mid=aux.length/2;
        
       if(aux.length%2!=0)            median=aux[mid];
        
        else                      median=(aux[mid]+aux[mid-1])/2.0;
        
        return median;
    }
    

    `


Log in to reply
 

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