寻找两个有序数组的中位数

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len1=nums1.size(),len2=nums2.size();

        if(len1>len2){
            vector<int> tmp=nums1;
            nums1=nums2;
            nums2=tmp;
            
            int tmp1=len1;
            len1=len2;
            len2=tmp1;
        }

        int mid=(len1+len2+1)/2;
        int left=0,right=len1;
        int max_of_left=INT_MIN,min_of_right=INT_MAX;

        while(left<=right){
            int i=(left+right)/2;
            int j=mid-i;

            if(i<len1 && nums1[i]<nums2[j-1]){
                left=i+1;
            }
            else if(i>0 && nums1[i-1]>nums2[j]){
                right=i-1;
            }
            else{
                if(i==0){
                    max_of_left=nums2[j-1];
                }
                else if(j==0){
                    max_of_left=nums1[i-1];
                }
                else{
                    max_of_left=max(nums1[i-1],nums2[j-1]);
                }

                if(((len1+len2)&1)==1){     //通过最后一位是0还是1,判断奇偶性
                    return max_of_left;
                }

                if(i==len1){
                    min_of_right=nums2[j];
                }
                else if(j==len2){
                    min_of_right=nums1[i];
                }
                else{
                    min_of_right=min(nums1[i],nums2[j]);
                }

                return (max_of_left+min_of_right)/2.0;
            }
        }
        return -1;

    }
};
posted @ 2020-03-07 15:41  7aughing  阅读(319)  评论(0编辑  收藏  举报