啥也不说,先上题!
1.leetode-寻找两个有序数组的中位数
题目描述
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。你可以假设 nums1 和 nums2 不会同时为空。
nums1 = [1, 3],nums2 = [2],则中位数是 2.0
解题思路
代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size();
int n2 = nums2.size();
if(n1>n2) return findMedianSortedArrays(nums2, nums1);
int imin=0, imax=n1;
while(imin<=imax){
int cut1=(imin+imax)/2;
int cut2 = (n1+n2)/2 - cut1;
int l1 = (cut1==0)?INT_MIN:nums1[cut1-1];
int l2 = (cut2==0)?INT_MIN:nums2[cut2-1];
int r1 = (cut1==n1)?INT_MAX:nums1[cut1];
int r2 = (cut2==n2)?INT_MAX:nums2[cut2];
if(l1>r2) imax = cut1-1;
else if(l2>r1) imin = cut1+1;
else return (n1+n2)%2 ? min(r1, r2):(max(l1,l2)+min(r1,r2))/2.0;
}
return 0.0;
}
};