- Median of Two Sorted Arrays
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
渣渣的我怎么做都会报错,懒得写了,直接上标准答案八。
本题思路:
1、把两个数组分成左右两份,而且长度必须要相等
2、我们要保证以下的两个条件,左边部分的总长度,等于右边部分的总长度,(当然如果总数是奇数的话左边会比右边的长度多一个数)。
len(left_part)=len(right_part)
max(left_part)≤min(right_part)
3、由于左边长等于右边长:i+j=m−i+n−j (or: m - i + n - j + 1m−i+n−j+1)
并且我们令n≥m, i=0∼m, j= (m+n+1)/2 -i;
4、所以开始后的时候我们设置较长的数组为n,较短的数组为m,i是m长度数组的下标,所以用i进行计数,令imax = m,imin = 0,且i初始值为(imax + imin)/2
5、利用二分法
if (i < iMax && B[j-1] > A[i]) 则 imax=i-1;
if (i > iMin && A[i-1] > B[j]) 则 imin = i+1;
6、找到i后,先确定其i,j是不是边界,如果是边界的话,要找出maxleft和minright(因为边界属于特殊情况),如果不是边界的话直接用通用方法找maxleft和minright。
7、找到这两个数后,判定m+n是否为奇数,如果是奇数就返回maxleft,如果是偶数则返回两者的平均值。
class Solution {
public double findMedianSortedArrays(int[] A, int[] B) {
int m = A.length;
int n = B.length;
if (m > n) { // to ensure m<=n
int[] temp = A; A = B; B = temp;
int tmp = m; m = n; n = tmp;
}
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 && B[j-1] > A[i]){
iMin = i + 1; // i is too small
}
else if (i > iMin && A[i-1] > B[j]) {
iMax = i - 1; // i is too big
}
else { // i is perfect
int maxLeft = 0;
if (i == 0) { maxLeft = B[j-1]; }
else if (j == 0) { maxLeft = A[i-1]; }
else { maxLeft = Math.max(A[i-1], B[j-1]); }
if ( (m + n) % 2 == 1 ) { return maxLeft; }
int minRight = 0;
if (i == m) { minRight = B[j]; }
else if (j == n) { minRight = A[i]; }
else { minRight = Math.min(B[j], A[i]); }
return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
}