4. Median of Two Sorted Arrays

本文介绍了一种高效算法,用于查找两个已排序数组的中位数,整体运行时间复杂度为O(log(m+n))。通过巧妙处理边界值,避免了传统方法的复杂性,附带详细代码及实例解析。

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

 

做这道题花费了个人大量时间,但做出来之后就觉得没那么难了,之前的思路,主要是对边界值的处理感觉太复杂理不清。以下思路在边界值方面更不容易搞混淆

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

solution 

class Solution {
   public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;
        int left = (n + m + 1) / 2;
        int right = (n + m + 2) / 2;
        return (getKthBigNum(nums1,0,nums2,0,left)+getKthBigNum(nums1,0,nums2,0,right))/2.0;
    }
    //函数目的为获取从小到大第K个数。
    //astart为A当前index,bStart同理,k为第k个大的数
    public int getKthBigNum(int [] A, int aStart, int []B,int bStart,int k){
        //取第k个大的数,如果有一个数组已经空了(到末尾),则第K个大的数另一个数组的的索引就为index + k -1
        int lenA=A.length,lenB=B.length;
        if(aStart>= lenA)
            return B[bStart + k-1];
        if(bStart>=lenB)
            return A[aStart + k-1];
        //若取第一个大数,即取其最小的值
        if(k==1){
            return Math.min(A[aStart],B[bStart]);
        }
        //目标将k降低到1,每次移除至多k/2个最小的数,
        int aindex = Math.min(lenA -1,aStart + k/2 - 1);
        int bindex = Math.min(lenB-1,bStart +k/2 -1);
        //index向右移动,移除较小的那一方
        if(A[aindex]>B[bindex]){
            return getKthBigNum(A,aStart,B,bindex+1,k-(bindex-bStart+1));
        }else{
            return getKthBigNum(A,aindex +1,B,bStart,k-(aindex-aStart+1));
        }
    }
}

这篇博客讲述的很全面: http://windliang.cc/2018/07/18/leetCode-4-Median-of-Two-Sorted-Arrays/,有图有代码有说明,本人参照其内容,完成了本题的编程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值