/*本题更一般化的形式为,查找两个数组中第k大的元素。
方法参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int total(m+n);
if(total & 0x1){
return find_kth_element(A, m, B, n, total/2 + 1);
}
else{
return ((double)find_kth_element(A, m, B, n, total/2)
+ find_kth_element(A, m, B, n, total/2+1))/2;
}
}
int find_kth_element(int A[], int m, int B[], int n, int k){
//保证m<=n
if(m > n) return find_kth_element(B, n, A, m, k);
if(m == 0) return B[k-1];
if(k == 1) return std::min(A[0], B[0]);
int ia = std::min(k/2, m), ib = k - ia;
if(A[ia-1] < B[ib-1]){
return find_kth_element(A + ia, m - ia, B, n, k - ia);
}
else if(A[ia-1] > B[ib-1]){
return find_kth_element(A, m, B + ib, n - ib, k - ib);
}
else{
return A[ia-1];
}
}
};
LeetCode之Median of Two Sorted Arrays
最新推荐文章于 2023-06-12 16:30:30 发布