Median of Two Sorted Arrays——Binary Search

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

题目

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

思路

给定的两个数组是有序数组,并且需要在时间复杂度为O(log(m+n)),所有应采用二分查找的方法,而中位数为有序数组为于中间位置的数值,所以只需要将两个有序数组一起分为个数相等的前后两部分就可以找到中位数,并且前后两部分一定是后面一部分的数值的最小值大于前面一部分数值的最大值。由于划分后的两部分的大小可以由两个数组的大小得到,在已知划分数组大小的情况下,确定一个数组的划分位置,就可以得到另一个数组的划分位置。而正确的划分位置应该保证划分位置左侧的一个数组的值小于划分位置右侧的另一个数组的值。这样就得到了确定划分位置的方法。而寻找划分位置的方法就可以采用二分法。最后得到的算法的时间复杂度为O(log(min(m, n)))。

代码

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        if(nums1.size() > nums2.size()){
            vector<int> temp = nums1;
            nums1 = nums2;
            nums2 = temp;
        }
        
        int m = nums1.size();
        int n = nums2.size();
        
        int totalLeft = (m + n + 1) / 2;
        
        int left = 0;
        int right = m;
        
        while(left < right){
            int i = left + (right - left + 1) / 2;
            int j = totalLeft - i;
            
            if(nums1[i-1] > nums2[j])
                right = i - 1;
            else
                left = i;
        }
        
        int i = left;
        int j = totalLeft - i;
        int nums1LeftMax = i == 0? INT_MIN: nums1[i-1];
        int nums1RightMin = i == m? INT_MAX: nums1[i];
        int nums2LeftMax = j == 0? INT_MIN: nums2[j-1];
        int nums2RightMin = j == n? INT_MAX: nums2[j];
        
        if((m + n) % 2 == 0)
            return float((max(nums1LeftMax, nums2LeftMax) + min(nums1RightMin, nums2RightMin))) / 2;
        else
            return max(nums1LeftMax, nums2LeftMax);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值