题目:
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)).
You may assume nums1 and nums2 cannot be both empty.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路,做到lg(m+n),一定是朝着二分去思考,每次扔掉待求位置前面的一半元素,保证二分,这里二分是对K,不同于之前数组的二分。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len = nums1.size() + nums2.size();
if(len % 2 == 0){
int tmp = findKth(nums1, 0, nums2, 0, len/2)
+ findKth(nums1, 0, nums2, 0, len/2+1);
return tmp / 2.0;
}
else{
return findKth(nums1, 0, nums2, 0, len/2+1);
}
}
// 拎清楚 Kth 是从1开始,而下标是从0开始。
// 涉及两者判断的要搞清楚边界情况
int findKth(vector<int> &nums1, int start1,
vector<int> &nums2, int start2,
int k)
{
// 刚开始写的是start1 > nums1.size()-1,
// nums1为空时通不过,因为size()返回无符号整数。
// 菜鸡,编码不规范,AC两行泪
if(start1 >= nums1.size()){
return nums2[start2 + k - 1];
}
if(start2 >= nums2.size()){
return nums1[start1 + k - 1];
}
if(k == 1){
return min(nums1[start1], nums2[start2]);
}
int Start1 = nums1.size() - start1 >= k / 2 ?
nums1[start1 + k / 2 - 1] : INT_MAX;
int Start2 = nums2.size() - start2 >= k / 2 ?
nums2[start2 + k / 2 - 1] : INT_MAX;
if(Start1 < Start2){
return findKth(nums1, start1 + k / 2, nums2, start2, k - k/2);
}
else{
return findKth(nums1, start1, nums2, start2 + k / 2, k - k/2);
}
}
};