LeetCode 4. 寻找两个有序数组的中位数

题目描述:

解法:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if(nums1.size()>nums2.size()) return findMedianSortedArrays(nums2,nums1);    //这一步必须要记得写,否则cut2会出现错误索引
        int m=nums1.size();
        int n=nums2.size();
        int Lmax1,Rmin1,Lmax2,Rmin2,cut1,cut2;
        int left=0,right=2*m;                       //增加虚拟位 #1#3# 
        while(left<=right){                        //二分nums1
            cut1=(left+right)/2;
            cut2=m+n-cut1;
            Lmax1=cut1<=0? INT_MIN:nums1[(cut1-1)/2];            //虚拟位寻址
            Rmin1=cut1>=2*m? INT_MAX:nums1[cut1/2];
            Lmax2=cut2<=0? INT_MIN:nums2[(cut2-1)/2];
            Rmin2=cut2>=2*n? INT_MAX:nums2[cut2/2];
            if(Lmax1>Rmin2){
                right=cut1-1;
            }
            else if(Lmax2>Rmin1){
                left=cut1+1;
            }
            else break;
        }
        return (max(Lmax1,Lmax2)+min(Rmin1,Rmin2))/2.0;
    }
};

参考:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/4-xun-zhao-liang-ge-you-xu-shu-zu-de-zhong-wei-shu/

posted @ 2019-09-03 16:32  DH_HUSTer  阅读(15)  评论(0编辑  收藏  举报