[leetcode] 4. 寻找两个有序数组的中位数
程序员文章站
2022-04-17 16:41:05
...
官方题解:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xun-zhao-liang-ge-you-xu-shu-zu-de-zhong-wei-shu-b/
class Solution {
public:
double findMedianSortedArrays(vector<int>& A, vector<int>& B) {
int m = A.size();
int n = B.size();
if(m > n)
{
vector<int> temp = A;
A = B;
B = temp;
m = A.size();
n = B.size();
}
int iMin = 0, iMax = m, halfLen = (n + m + 1)/2;
while(iMin <= iMax)
{
int i = (iMin+iMax)/2; //0 <= i <= m;
int j = halfLen - i;
if(i < iMax && B[j-1] > A[i])
{//i < m ==> j > 0
//并且m < n ==> j <= n
iMin = i + 1; //too small
}
else if(i > iMin && A[i-1] > B[j])
{//i > 0 ==> j < n
//并且m < n ==> j >= 0
iMax = i - 1; //too big
}
else
{
double maxLeft = 0;
if(i == 0){ maxLeft = B[j-1]; }
else if(j == 0) { maxLeft = A[i-1]; }
else { maxLeft = 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 = min(A[i], B[j]); }
return (maxLeft + minRight)/2.0;
}
}
return 0.0;
}
};
m <= n的作用:
if(i < iMax && B[j-1] > A[i])
{//i < m ==> j > 0
//并且m < n ==> j <= n
iMin = i + 1; //too small
}
由i < m ==> j > 0
,但是,这个时候j
会大于n
吗?
不会,因为i
是大于等于0
小于等于m
的,由m <= n
(一开始保证了) 可以推出j < = n
,因为i
越小,j
就越大,i == 0
时,j
最大,j = (m + n + 1) /2 - 0 <= (2n + 1)/2 <= n
(int运算)
else if(i > iMin && A[i-1] > B[j])
{//i > 0 ==> j < n
//并且m < n ==> j >= 0
iMax = i - 1; //too big
}
这个也是同理,由i > 0 ==> j < n
,由m < n ==> j >= 0
,因为i
越大,j
就越小,i == m
时,j
最大,j = (m + n + 1) /2 - m >= (n - m + 1)/2 >= 0
(int运算,m <= n
)
上一篇: 448. 找到所有数组中消失的数字
下一篇: Leetcode 160. 相交链表