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)).
Subscribe to see which companies asked this question
实现:
class Solution {
public:
double getkth(vector<int>& a, int sa, vector<int>& b, int sb, int k)
{
if (sa+1 > a.size()) return b[sb + k -1];
if (sb+1 > b.size()) return a[sa + k - 1];
if (k == 1) return min(a[sa], b[sb]);
int amid = INT_MAX;
int bmid = INT_MAX;
if (sa + k/2 -1 < a.size()) amid = a[sa + k/2 - 1];
if (sb + k/2 -1 < b.size()) bmid = b[sb + k/2 - 1];
if (amid < bmid) {
return getkth(a, sa + k/2, b, sb, k - k/2);
} else {
return getkth(a, sa, b, sb + k/2, k - k/2);
}
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int l = (nums1.size() + nums2.size() + 1) /2;
int r = (nums1.size() + nums2.size() + 2) /2;
return (getkth(nums1, 0, nums2, 0, l) + getkth(nums1, 0, nums2, 0, r)) / 2.0;
}
};