leetcode_【4】寻找两个有序数组的中位数

1.题目描述

给定两个大小为 m 和 n 的有序数组 nums1nums2

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

你可以假设 nums1nums2 不会同时为空。

示例 1:

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

则中位数是 2.0

示例 2:

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

则中位数是 (2 + 3)/2 = 2.5

2.解题思路

方法1:

  • 排序输出中间值,但是复杂度不符合题意

方法2:

  • 滑动窗口思想

3.代码

方法1:复杂度不符合

public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //将两个数组放到一个数组中并从小到大排序
        int[] ints = ArrayUtils.addAll(nums1, nums2);
        Arrays.sort(ints);
        //奇数个数返回 中间索引,偶数个返回最中间的两个数的平均,注意/2可能为小数,要/2d或者/2.0强转为double类型
        if(ints.length%2==0){
            return (ints[(ints.length+1)/2]+ints[(ints.length+1)/2-1])/2d;
        }else return ints[(ints.length-1)/2];
    }

方法2:复杂度还是不符合

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n1Length = nums1.length;
        int n2Length = nums2.length;
        int totalLength = n1Length + n2Length;
        int arrayIndex = 0;
        int maxArrayIndex = totalLength / 2;
        int n1Index = 0;
        int n2Index = 0;

        int last1 = 0;
        int last2 = 0;  //用于记录偶数情况下的last1的前一个数
        while (arrayIndex <= maxArrayIndex) {
            last2 = last1;
            //只剩下nums2的情况了,nums1的全部数跟nums2排序都还没到达中间
            if (n1Index >= n1Length) {
                last1 = nums2[n2Index++];
            //只剩下nums1的情况了,nums2的全部数跟nums1排序都还没到达中间
            } else if (n2Index >= n2Length) {
                last1 = nums1[n1Index++];
            } else {
                //哪个小哪个索引坐标【n1Index或者n2Index】开始滑动
                if (nums1[n1Index] <= nums2[n2Index]) {
                    last1 = nums1[n1Index++];
                } else {
                    last1 = nums2[n2Index++];
                }
            }
            //整体数组【nums1 U nums2】的索引每循环依次自增1,直到到达整体数组中间位置
            arrayIndex++;
        }
        if (totalLength % 2 == 0) {
            return (last1 + last2) / 2.0;
        } else {
            return last1;
        }
    }
}

4.提交记录

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值