Description
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
1 2 3
| Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
|
Example 2:
1 2 3
| Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
|
1 2 3 4 5 6 7 8
| Constraints:
nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i], nums2[i] <= 106
|
Approach: Binary Search
1 2
| nums1: [0 .. i-1] | [i .. m-1] nums2: [0 .. j-1] | [j .. n-1]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1.length > nums2.length) { return findMedianSortedArrays(nums2, nums1); } int m = nums1.length; int n = nums2.length; int imin = 0, imax = m, halfLen = (m + n + 1) / 2; while (imin <= imax) { int i = (imin + imax) / 2; int j = halfLen - i; if (i < imax && nums1[i] < nums2[j - 1]) { imin = i + 1; } else if (i > imin && nums1[i - 1] > nums2[j]) { imax = i - 1; } else { int maxLeft = 0; if (i == 0) { maxLeft = nums2[j - 1]; } else if (j == 0) { maxLeft = nums1[i - 1]; } else { maxLeft = Math.max(nums1[i - 1], nums2[j - 1]); }
if ((m + n) % 2 == 1) { return maxLeft; }
int minRight = 0; if (i == m) { minRight = nums2[j]; } else if (j == n) { minRight = nums1[i]; } else { minRight = Math.min(nums2[j], nums1[i]); }
return (maxLeft + minRight) / 2.0; } } return 0.0; } }
|
Approach: Two Pointers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1.length > nums2.length) { return findMedianSortedArrays(nums2, nums1); } int len1 = nums1.length; int len2 = nums2.length; int left = 0, right = len1;
while (left <= right) { int p1 = left + (right - left) / 2; int p2 = (len1 + len2 + 1) / 2 - p1;
int left1 = p1 == 0 ? Integer.MIN_VALUE : nums1[p1 - 1]; int right1 = p1 < len1 ? nums1[p1] : Integer.MAX_VALUE;
int left2 = p2 == 0 ? Integer.MIN_VALUE : nums2[p2 - 1]; int right2 = p2 < len2 ? nums2[p2] : Integer.MAX_VALUE; if (left1 <= right2 && left2 <= right1) { if ((len1 + len2) % 2 == 0) { return (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0; } return Math.max(left1, left2); } if (left1 > right2) { right = p1 - 1; } else { left = p1 + 1; } } return 0.0;
} }
|