Java Solution, Very Easy To understand.


  • -2
    T

    Hope it helps!

    public static double findMedian(int[] nums1, int[] nums2){
    	int l1 = nums1.length;
    	int l2 = nums2.length;
    	int total = l1+l2;
    	int t[]=new int[total]; 
    	int i=0,j=0,m=0;
    
    	for (m =0 ;m<total&&i<l1&&j<l2;m++)
    	{
    		if(nums1[i]>nums2[j])
    		{
    			t[m]=nums2[j];
    			j++;
    		}
    		else {
    			t[m]=nums1[i];
    			i++;
    		}
    	}
    	
    	if (i==l1)
    		System.arraycopy(nums2, j, t, m, nums2.length - j);
    	else 
    		System.arraycopy(nums1, i, t, m, nums1.length - i);
    	
    	if (total%2!=0)
    		return t[total/2];
    	else 
    		return (double)(t[total/2] + t[total/2-1])/2;
    }

  • 0
    G

    You running time is O(m+n) rather than O(log(m+n)).

    And you only need to fill half of the array t if you want to do this way.

    In addition, you don't need array t, since no element before t[mid] is used. one variable that counts the num of elements compared can satisfy you idea.


Log in to reply
 

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