categories: leetcode
题目描述
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]
参考代码
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if (m > n) {
int[] tmp = nums1; nums1 = nums2; nums2 = tmp;
int temp = m; m = n; n = temp;
}
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 && nums2[j-1] > nums1[i]) {
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;
}
}
思路及总结
当找到目标对象 ii时,中位数为:
当为奇数时,left的数字较多,可以举例来理解一下
保证奇偶都能满足
最后的那个数学证明是看到头都大了,大概是那个道理。还是官方解答,最为致命。时间复杂度为log(m+n),意思就是只能单层循环一次两个数组,有点利用二分法和分治的思想。
参考
https://leetcode.com/problems/median-of-two-sorted-arrays/solution/