Why can't we use mergesort to make a single array ?


  • -1
    G

    class Solution {

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

            int nums1Length = nums1.length;
    	int nums2Length = nums2.length;
    	int totalItems = nums1Length+nums2Length;
    	int[] newArray = new int[totalItems];
    	int i=0,j=0,k=0;
    	
    	while(i<nums1Length && j<nums2Length){
    		 if(nums1[i] <= nums2[j]){
    			newArray[k] = nums1[i];
    			k++;i++;
    		} else {
    			newArray[k] = nums2[j];
    			k++;j++;
    		}
    	}
    	
    	while(i<nums1Length){
    		newArray[k] = nums1[i];
    		i++;k++;
    	}
    	
    	while(j<nums2Length){
    		newArray[k] = nums2[j];
    		j++;k++;
    	}
    	
    	double value = 0.0;
    	
    	if(totalItems%2 != 0){
    		int mid = totalItems/2;
    		value = (double)newArray[mid];
    	} else{
    		int midPos1 = totalItems/2;
    		int midPos2 = midPos1-1;
    		double value1 = (double)newArray[midPos1];
    		double value2 = (double)newArray[midPos2];
    		value = (value1+value2)/2;
    	}
    	
    	return value;
    }
    

    }


  • 0

    Because that isn't O(log(m+n)).


Log in to reply
 

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