二分思路求解——Median of Two Sorted (寻找两个正序数组的中位数)_C++

【链接】https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

题目:‌

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. 

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

You may assume nums1 and nums2 cannot be both empty. 

Example 1: 

nums1 = [1, 3] nums2 = [2] The median is 2.0

‌Example 2: 

nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5

思路:

 

一般如果题目要求时间复杂度在O(log(n)),大部分都是可以使用二分的思想来进行求解。

  • 简单说来

本题是两个数组,也是一样的,我们先求出两个数组长度之和。如果为奇数,就找中间的那个数,也就是 (长度之和 1)/2 。如果为偶数,那就找 长度之和/2。此时,问题其实已经转化为“找到两个数组中第k小的元素”。找到了第k位之后,第k+1位我们已经知道了,然后第k位和第k+1位的和,除以2就是我们要找的中位数。

  • 其他方案比较
  1. 这⼀题最容易想到的办法是把两个数组合并,然后取出中位数。但是合并有序数组的操作是O(max(n,m)) 的,不符合题意。看到题⽬给的 log 的时间复杂度,很容易联想到⼆分搜索。

  2. 由于要找到最终合并以后数组的中位数,两个数组的总⼤⼩也知道,所以中间这个位置也是知道的。只需要⼆分搜索⼀个数组中切分的位置,另⼀个数组中切分的位置也能得到。为了使得时间复杂度最⼩,所以⼆分搜索两个数组中⻓度较⼩的那个数组。

 

代码:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int size1 = nums1.size();
        int size2 = nums2.size();
        int total = size1+size2;
        int left = (total + 1)/2;
        int right = (total + 2)/2;
        return (findK(nums1,0,nums2,0,left) + findK(nums1,0,nums2,0,right))/2.0;
    }

    int findK(vector<int>& nums1,int i, vector<int>& nums2,int j, int k){
        if(i >= nums1.size())return nums2[j + k - 1];
        if(j >= nums2.size())return nums1[i + k - 1];
        if(k == 1)return std::min(nums1[i],nums2[j]);
        //计算出每次要比较的两个数的值,来决定 "删除"" 哪边的元素
        int mid1 = (i + k/2 -1)<nums1.size()?nums1[i + k/2 -1]:INT_MAX;
        int mid2 = (j + k/2 -1)<nums2.size()?nums2[j + k/2 -1]:INT_MAX;
        //二分趋近
        if(mid1 < mid2){
            return findK(nums1,i+k/2,nums2,j,k-k/2);
        }
        return findK(nums1,i,nums2,j+k/2,k-k/2);
    }
};

 

参考:

【寻找两个正序数组的中位数(292)】

https://www.geekxh.com/1.99.%E5%85%B6%E4%BB%96%E8%A1%A5%E5%85%85%E9%A2%98%E7%9B%AE/21.html#_02%E3%80%81%E9%A2%98%E7%9B%AE%E5%88%86%E6%9E%90

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

聊聊技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值