此题归在二分法中:
大概思想:将两个数组分别分为两个部分,两者的数值较小的数字,就是合并后数组的前半部分
难点在:找到第一个数组的位置i,则第二数组的位置j = (m+n +1)/2 - i;
此后,由i,j找到中位数,如果m+n为奇数,则max_left即为所求,否则:(max_left + min_right)/2为结果
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size();
int n = nums2.size();
if(m > n)return findMedianSortedArrays(nums2,nums1);
int left = 0;
int right = m;
int i = -1;
int j = -1;
while(true){
i = (left + right) / 2;
j = (m + n + 1) / 2 - i;
if((i == 0 || j == n || nums1[i-1] <= nums2[j]) && (j == 0 || i == m || nums2[j-1] <= nums1[i])){
break;
}else if(i > 0 && nums1[i-1] > nums2[j]){
right = i - 1;
}else if(j > 0 && nums2[j-1] > nums1[i]){
left = i + 1;
}
}
//find the median num
int max_left = -1;
int min_right = -1;
if(i == 0){
max_left = nums2[j-1];
}else if(j == 0){
max_left = nums1[i-1];
}else{
max_left = max(nums2[j-1] , nums1[i-1]);
}
if((m+n) % 2){
return max_left;
}
if(i == m){
min_right = nums2[j];
}else if(j == n){
min_right = nums1[i];
}else{
min_right = min(nums2[j] , nums1[i]);
};
return double(max_left + min_right) / 2;//保证中位数的准确性
}
};