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)).

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(NlogN),所以自然就想到了二分法。

由于数组存在空或者指针越界的危险,所以我们在两个数组的末尾添加一个大整数。

        nums1.insert(nums1.end(), INT_MAX);
        nums2.insert(nums2.end(), INT_MAX);
在中间部分我们的循环主题主要是保证我们循环停止在两个数组长度和的中间部分,即(len1 + len2)/ 2。通过两个指针start1和start2来完成移动寻找。

最后我们对数组1和2的长度之和分奇偶讨论。

三、代码

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size();
        int len2 = nums2.size();
        if(len1 + len2 == 0) return 0;
        nums1.insert(nums1.end(), INT_MAX);
        nums2.insert(nums2.end(), INT_MAX);
        int start1 = 0, start2 = 0;
        int new_mid,old_mid;
        for(int i = 0; i <= (len1 + len2) / 2; ++i){
            old_mid = new_mid;
            if(nums1[start1] > nums2[start2]) new_mid = nums2[start2++];
            else new_mid = nums1[start1++];
        }
        if((len1 + len2) % 2 == 1) return new_mid;
        else return ((double)new_mid + (double)old_mid) / 2;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

fullstack_lth

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

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

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

打赏作者

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

抵扣说明:

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

余额充值