4. Median of Two Sorted Arrays

本文介绍了一种在O(log(m+n))时间内找出两个已排序数组中位数的方法,通过二分查找确保时间复杂度,适用于统计学场景,其中数组长度不同时,调整索引确保正确计算。

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

Description

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

You may assume nums1 and nums2 cannot be both empty.

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

Problem URL


Solution

给两个已经排序的数组,至少有一个非空,在O(log(m + n)) 的时间里找到两个数组的中位数。在统计学上,中位数的作用是将一组数分成个数相同的两部分,并且左半部分的最大值小于等于右半部分的最大值。这就是我们进行二分查找的依据。

First, make sure num2.length > num1.length, because the calculated j value may exceed the range of second array. Using I denotes the index of min value of nums1’s right part. J denotes the index of min value of nums2’ right. While imin <= imax(= for return value, because I is confirmed). If nums1[I -1] > nums2[j], it means I is to big. Vice versa. Then according the number of sum, return leftMax or average.

Code
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length){
            return findMedianSortedArrays(nums2, nums1);
        }
        int l1 = nums1.length, l2 = nums2.length;
        int imin = 0, imax = nums1.length, halfSum = (l1 + l2 + 1) / 2;
        while (imin <= imax){
            int i = (imin + imax) / 2;
            int j = halfSum - i;
            if (i < l1 && nums2[j -1] > nums1[i]){// i is too small
                imin = i + 1;
            }
            else if (i > 0 && nums1[i - 1] > nums2[j]){//i is too big
                imax = i - 1;
            }
            else{
                int leftMax = Integer.MIN_VALUE;
                if (i == 0){
                    leftMax = nums2[j - 1];
                }
                else if (j == 0){
                    leftMax = nums1[i - 1];
                }
                else{
                    leftMax = Math.max(nums1[i - 1], nums2[j - 1]);
                }
                if ((l1 + l2) % 2 == 1){//odd sum number
                    return leftMax;
                }
                
                int rightMin = Integer.MAX_VALUE;
                if (i == l1){
                    rightMin = nums2[j];
                }
                else if (j == l2){
                    rightMin = nums1[i];
                }
                else{
                    rightMin = Math.min(nums1[i], nums2[j]);
                }
                return (rightMin + leftMax) / 2.0;
            }
        }
        return 0;
    }
}

Time Complexity: O(log(m+n))
Space Complexity: O(1)


Review
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值