Easy & short Java solution.Better than the toppest one! 0.5*O(m+n) time complexity!


  • 0
    Y

    Similar to merge sort, 0.5*O(m+n) time complexity! Enjoy!

            public static double findMedianSortedArrays(int[] nums1, int[] nums2)
    	{
    		int totalLength = nums1.length + nums2.length;
    		int pos = totalLength / 2;
    		int r1 = 0, r2 = 0;
    		for (int i = 0, a = 0, b = 0, t1, t2; i < pos + 1; i++)
    		{
    			t1 = a < nums1.length ? nums1[a] : Integer.MAX_VALUE;
    			t2 = b < nums2.length ? nums2[b] : Integer.MAX_VALUE;
    			r2 = r1;
    			r1 = t1 < t2 ? nums1[a++] : nums2[b++];
    		}
    		return totalLength % 2 == 0 ? (r1 + r2) / 2.0 : r1;
    	}
    

Log in to reply
 

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