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

本文介绍了一种方法来寻找两个已排序数组的中位数。通过合并两个数组为一个有序数组,并从中找到中位数。这种方法仅需遍历两次数组即可完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题目描述:给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)

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

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:有序数组合并

将2个数组按顺序合并到一个大数组里面,2个数组都只会遍历一次。然后在大数组中获取中位数。

解法二:待完成

思考怎么在 时间复杂度为 O(log (m+n))下完成?

public class Solution {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] allNums = new int[nums1.length + nums2.length];
        int i = 0, j = 0, x = 0;
        int num1 = Integer.MAX_VALUE, num2 = Integer.MAX_VALUE;
        for (; i < nums1.length || j < nums2.length; ) {
            if (i < nums1.length) {
                num1 = nums1[i];
            }
            if (j < nums2.length) {
                num2 = nums2[j];
            }
            if (num1 < num2) {
                allNums[x] = num1;
                i++;
            } else {
                allNums[x] = num2;
                j++;
            }
            x++;
            num1 = Integer.MAX_VALUE;
            num2 = Integer.MAX_VALUE;
        }
        int count = nums1.length + nums2.length;
        if (count % 2 == 1) {
            return allNums[count / 2];
        } else {
            return ((double) (allNums[count / 2 - 1] + allNums[count / 2])) / 2;
        }
    }
​
    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2};
        int[] nums2 = new int[]{3, 4};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

醉舞经阁-半卷书

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

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

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

打赏作者

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

抵扣说明:

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

余额充值