LeetCode 4. 寻找两个正序数组的中位数
原题链接
困难
作者:
__43
,
2020-09-22 20:12:32
,
所有人可见
,
阅读 355
class Solution {
public:
double findMedianSortedArrays(vector<int>& n1, vector<int>& n2)
{
if (n1.size() > n2.size())
swap(n1, n2);
int n = n1.size(), m = n2.size();
int NLmax, NRmin, MLmax, MRmin, l = 0, r = n, c1, c2;
while (1)
{
c1 = l + r >> 1;
c2 = (m + n + 1 >> 1) - c1;
NLmax = 0 == c1 ? INT_MIN : n1[c1 - 1];
NRmin = n == c1 ? INT_MAX : n1[c1];
MLmax = 0 == c2 ? INT_MIN : n2[c2 - 1];
MRmin = m == c2 ? INT_MAX : n2[c2];
if (NLmax > MRmin) r = c1 - 1;
else if (MLmax > NRmin) l = c1 + 1;
else break;
}
if ((m + n) & 1) return max(MLmax, NLmax);
else return (max(MLmax, NLmax) + min(NRmin, MRmin)) * 0.5;
}
};