Description
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)).
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
解:
假設nums1的長度小于nums2的長度:
- 以i将nums1劃分為兩部分nums1_l和nums1_r,同時有 r=m+n+12 将nums2劃分為兩部分nums2_l和nums2_r
- 劃分之後,将兩個數組對應的左右部分分别對應,如下表:
left | right |
---|---|
nums1_1 | nums1_r |
nums2_l | nums2_r |
當滿足以下兩個條件時:
- i+j=m−i+n−j
- nums2[j−1]≤nums1[i] and nums1[i−1]≤nums2[j]
可以得到中值:
- 若 m+n 為奇數,中值為: max(nums1[i−1],nums2[j−1])
- 否則,中值為: max(nums1[i−1],nums2[j−1])+min(nums1[i],nums2[j])2
Java代碼:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
// 確定n大于m
if (m > n) {
int[] temp = nums1; nums1 = nums2; nums2 = temp;
int tmp = m; m = n; n = tmp;
}
int iMin = , iMax = m, halfLen = (m + n + ) / ;
while (iMin <= iMax) {
int i = (iMin + iMax) / ;
int j = halfLen - i;
if (i < iMax && nums2[j-] > nums1[i]){
// i的值太小
iMin = iMin + ;
}
else if (i > iMin && nums1[i-] > nums2[j]) {
// i的值太大
iMax = iMax - ;
}
else {
int maxLeft = ;
// 計算左半部分的最大值
if (i == ) { maxLeft = nums2[j-]; }
else if (j == ) { maxLeft = nums1[i-]; }
else { maxLeft = Math.max(nums1[i-], nums2[j-]); }
// 兩個數組的長度之和為奇數時,中值為長度的中間值
if ( (m + n) % == ) { return maxLeft; }
// 當兩個數組的長度之和為偶數時, 中值等于左半部分的最大值與右半部分的最小值的均值
int minRight = ;
if (i == m) { minRight = nums2[j]; }
else if (j == n) { minRight = nums1[i]; }
else { minRight = Math.min(nums2[j], nums1[i]); }
return (maxLeft + minRight) / ;
}
}
return ;
}
}