4. Median of Two Sorted Arrays - Hard
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
基于kth smallest element in two sorted array
time: O(log(M + N)), space: O(logk) -- kth的额外空间复杂度是O(1), 调用logk次 -> O(logk)
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int k = (nums1.length + nums2.length) / 2; int m1 = kth(nums1, 0, nums2, 0, k + 1); if((nums1.length + nums2.length) % 2 == 0) { int m2 = kth(nums1, 0, nums2, 0, k); return (double)(m1 + m2) / 2.0; } return m1; } public int kth(int[] A, int aleft, int[] B, int bleft, int k) { if(aleft >= A.length) { return B[bleft + k - 1]; } if(bleft >= B.length) { return A[aleft + k - 1]; } if(k == 1) { return Math.min(A[aleft], B[bleft]); } int amid = aleft + k / 2 - 1; int bmid = bleft + k / 2 - 1; int aval = amid >= A.length ? Integer.MAX_VALUE : A[amid]; int bval = bmid >= B.length ? Integer.MAX_VALUE : B[bmid]; if(aval <= bval) { return kth(A, amid + 1, B, bleft, k - k / 2); } else { return kth(A, aleft, B, bmid + 1, k - k / 2); } } }