#include <iostream>
#include <vector>
using namespace std;
// 不是一直在查找中值,而是一直查找前k个值,每次去掉一部分值,k也相应减小,直到减到1为止,这样就可以算出结果
// time complexity O(log(m+n)) space complexity O(log(m+n))
class Solution
{
public:
double findMedianSortedArrays(const vector<int>& A, const vector<int>& B)
{
const int m=A.size();
const int n=B.size();
int total = m+n;
if (total & 0x1) // 按位与, 判断奇偶 total为奇数
return find_kth(A.begin(), m, B.begin(), n, total/2+1); // 奇数找到中间值就行
else // total 为偶数
return (find_kth(A.begin(), m, B.begin(), n, total/2)
+find_kth(A.begin(), m, B.begin(), n, total/2+1))/2.0; // 偶数找到中间的两个值/2.0
}
private:
static int find_kth(std::vector<int>::const_iterator A, int m, std::vector<int>::const_iterator B, int n, int k) //调用这个函数不会访问或者修改任何对象(非static)数据成员
{
//always assume that m is equal or smaller than n
if (m>n)
return find_kth(B, n, A, m, k);
if (m==0)
return *(B+k-1); // B的median
if (k==1)
return min(*A, *B); // 找最小值, 这个排序从小往大排序,第一位就是最小值 已经能定位中值了
//divide k into two parts
int ia=min(k/2, m), ib=k-ia; // 在这可以看出为啥假设m is equal or smaller than n A中取k/2或是全取, 然后B中取补齐k个元素
if (*(A+ia-1)<*(B+ib-1)) // 比较所取的最大值, 如果最大值A<B,则将A的前ia个数抛弃, A>B,则抛弃B的前ib个值,如果两个值相等,则找到了第k个值
return find_kth(A+ia, m-ia, B, n, k-ia);
else if(*(A+ia-1) > *(B+ib-1))
return find_kth(A, m, B+ib, n-ib, k-ib);
else
return A[ia-1];
}
};
int main()
{
vector<int> a = {1,3};
vector<int> b = {2};
Solution s;
double result;
result = s.findMedianSortedArrays(a, b);
cout << result << endl;
// cout << (1&0x1) << endl;
// cout << (2&0x1) << endl;
}
leetcode find kth
猜你喜欢
转载自www.cnblogs.com/o-v-o/p/9979922.html
今日推荐
周排行