码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-03-07 16:01:41      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:int   有序   while   数组   tmp   中位数   cto   else   class   

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;

    }
};

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

标签:int   有序   while   数组   tmp   中位数   cto   else   class   

原文地址:https://www.cnblogs.com/zijidan/p/12434651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!