LeetCode 4 寻找两个正序数组的中位数

题目描述:

给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2

请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

 

示例 1:

nums1 = [1, 3]
nums2 = [2]

则中位数是 2.0

因为两个数组都是正序数组,所以中位数可以直接根据顺序找到中间的一个或两个数字(根据奇偶区别)即可。

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        double res = 0;
        int l1 = nums1.length,l2 = nums2.length;
        //判断奇偶
        int ex = (l1+l2+1)%2;
        //记录上一个数,中位数需要取两个时使用
        double temp = 0;
        int n1=0,n2=0;
        for(int i=0;i<=(l1+l2)/2;i++){
            //每次去较小的那个数即可
            if(n1<l1&&n2<l2){
                if(nums1[n1]<nums2[n2]){
                    temp = res;
                    res = nums1[n1];
                    n1++;
                }else{
                    temp = res;
                    res = nums2[n2];
                    n2++;
                }
            }else{
                if(n1<l1){
                    temp = res;
                    res = nums1[n1];
                    n1++;
                }else{
                    temp = res;
                    res = nums2[n2];
                    n2++;
                }
            }
            
        }
        if(ex>0){
            res = (temp + res)/2;
        }
        return res;
    }
}

时间复杂度(m+n)/2 空间复杂度(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值