题目:
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.
解法:
假想两个数组合并成长度为m+n的nums,现在要为nums的左半部分找到int (m+n)/2
个数。
假设nums1的长度比nums2小,那么操作nums1。
以二分法确定nums1的切割点。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m=nums1.size(), n=nums2.size();
//保证nums1是最短的
if(m>n) return findMedianSortedArrays(nums2, nums1);
//操作短数组,这样长数组不会越界
int left_num = (m + n) / 2;
int cut1, cut2, left=0, right=m, nums1_left_max, nums1_right_min, nums2_left_max, nums2_right_min;
while(left<=right){
cut1 = (left + right) / 2; //左侧有cut1个数
cut2 = left_num - cut1;
//如何处理左右两个边界:1、哨兵(有成本)2、每次都判断
nums1_left_max = cut1==0 ? INT_MIN : nums1[cut1-1];
nums1_right_min = cut1==m ? INT_MAX : nums1[cut1];
nums2_left_max = cut2==0 ? INT_MIN : nums2[cut2-1];
nums2_right_min = cut2==n ? INT_MAX : nums2[cut2];
//二分
if(nums1_left_max>nums2_right_min) right = cut1 - 1; //cut1左移
else if(nums2_left_max>nums1_right_min) left = cut1 + 1; //cut1右移
else break; //循环条件取等号目的是永远在这里退出while
}
if((m+n)%2==1) return double(min(nums1_right_min, nums2_right_min));
else return (max(nums1_left_max, nums2_left_max) + min(nums1_right_min, nums2_right_min))/2.0;
}
};