Median of Two Sorted Arrays

Given two sorted arrays nums1 and nums2 of size m and n respectively.

Return the median of the two sorted arrays.

Follow up: The overall run time complexity should be O(log (m+n)).

 

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Example 3:

Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Example 4:

Input: nums1 = [], nums2 = [1]
Output: 1.00000
Example 5:

Input: nums1 = [2], nums2 = []
Output: 2.00000
 

Constraints:

nums1,length == m
nums2,length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int n=nums1.size();
        int m=nums2.size();
        if(n>m)
        {
            return findMedianSortedArrays(nums2,nums1);
            //为了便于编码,保证nums1是长度小的数组
        }
        int LMax1,LMax2,RMin1,RMin2;//分界处的点
        int c1,c2;//nums1,nums2左半段的长度
        int left=0,right=2*n;
        //加上虚拟的'#',nums1的长度为2*n+1;
        //例子:#1#4#7#9# #2#3#8#
        //虚拟之后,LMaxi = (Ci-1)/2 位置上的元素
        //RMini = Ci/2 位置上的元素
        while(left <= right)//二分
        {
            c1=(left+right)/2;
            c2 = m+n-c1;
            LMax1 = (c1 == 0) ? INT_MIN : nums1[(c1-1)/2];
            RMin1 = (c1 == 2*n) ? INT_MAX :nums1[c1/2];
            LMax2 = (c2 == 0) ? INT_MIN : nums2[(c2-1)/2];
            RMin2 = (c2 == 2*m)? INT_MAX :nums2[c2/2];
            if(LMax1 > RMin2)
            right = c1-1;
            else if(LMax2 >RMin1)
            left = c1+1;
            else
            break;//都满足的话则找到了
        }
        return (max(LMax1,LMax2)+min(RMin1,RMin2))/2.0;
    }
};

注意:1.log(m+n)则限定为二分查找的方式实现 2.划分界限,找到中位数 3.加入虚拟的"#",来实现奇数和偶数的讨论

posted @ 2020-08-22 11:51  zmachine  阅读(121)  评论(0编辑  收藏  举报