C++は2つの正の配列の中位数を探します


        m   n    (    )   nums1   nums2。

               ,              O(log(m + n))。

      nums1   nums2       。

 

   1:

nums1 = [1, 3]
nums2 = [2]

      2.0
   2:

nums1 = [1, 2]
nums2 = [3, 4]

      (2 + 3)/2 = 2.5

 
class Solution {
public:
    double findMedianSortedArrays(vector& nums1, vector& nums2) {
            if(nums1.size() > nums2.size()){
                return findMedianSortedArrays(nums2,nums1);
            }

            int m = nums1.size();
            int n = nums2.size();
            int left = 0,right=m,ansi = -1;
            int median1 =0,median2 = 0;

            while(left<=right){
                int i=(left + right)/2;
                int j=(m+n+1)/2 - i;
                
                int nums_im1 = (i==0?INT_MIN:nums1[i-1]);
                int nums_i = (i==m?INT_MAX:nums1[i]);
                int nums_jm1 = (j==0?INT_MIN:nums2[j-1]);
                int nums_j = (j==n?INT_MAX:nums2[j]);
                if(nums_im1<=nums_j){
                    ansi = i;
                    median1 = max(nums_im1,nums_jm1);
                    median2 = min(nums_i,nums_j);
                    left = i+1;
                }
                else{
                    right = i-1;
                }


            }

            return (m+n)%2 == 0?(median1+median2)/2.0:median1;

    }
};