LeetCode 4. Median of Two Sorted Arrays

4 篇文章 0 订阅
1 篇文章 0 订阅

题目描述

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(log(m+n));
开始时我使用线性扫描的方式找到中间值,但是就不满足时间复杂度要求了。
然后参考了别人的一个解答@参考代码,使用二分查找。
比较难理解。

代码

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
    {
        int m=nums1.size(),n=nums2.size();
        int K=(m+n)/2;
        if(m+n == 0)
        {
            return -1;
        }
        else if((m+n)%2==1)//odd
        {
            return findKth(nums1,0,m,nums2,0,n,K);
        }
        else //even
        {
            return (findKth(nums1,0,m,nums2,0,n,K) + findKth(nums1,0,m,nums2,0,n,K-1))/2;
        }
    }

    double findKth(vector<int>&nums1,int L1,int len1,vector<int>&nums2,int L2,int len2,int K)
    {
        if(len1>len2)
        {
            return findKth(nums2,L2,len2,nums1,L1,len1,K);
        }
        if(len1 == 0)//如果第一个数组为空
        {
            return (double) nums2[L2+K];
        }
        if(K==len1+len2-1)//最终会变为找两个数组中的最大值?????为什么
        {
            return (double)max(nums1[L1+len1-1],nums2[L2+len2-1]);
        }
        int i = len1/2;//二分查找
        int j = K-i;
        if(nums1[L1+i]>nums2[L2+j])
        {
            return findKth(nums1,L1,i,nums2,L2+j,len2-j,i);//去掉L2前面的j个数,去掉L1以及L1之后的数,处理后找下标为K-j=i的数
        }
        else
        {
            return findKth(nums1,L1+i,len1-i,nums2,L2,j,j);//去掉L1前面的i个数,去掉L2以及L2之后的数,处理后找下标为K-i=j的数
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值