156.Median of Two Sorted Arrays

本文介绍了一种寻找两个有序数组中位数的方法,该方法的时间复杂度为O(log(m+n))。通过确定中位数在排序后的数组中的位置,文章详细解释了如何在不完全合并两个数组的情况下找到中位数。

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

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

Subscribe to see which companies asked this question.

分析:如果两个数组长度之和为偶数,则需要中间的两个数字;如果两个数组长度之和为奇数,则只需要最中间的那个数字。

所以第一步,先分别计算两个数组的长度,然后确定可能作为中位数的两个数字在整体排序之后的下标,首先计算出低下标对应的值,然后再计算出高下标对应的值。

需要注意的是,在给两个数组进行排序的过程中可能会出现某个数组走到尽头的情况,要注意区分。

 /**
    * 分别用m和n表示两个数组的长度。
    * 新定义两个数字表示中间的两个数字。
    * 根据m和n的大小求出两个数组的中位数在整体数组排序中的位置。
    */
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        
        int m = nums1.length;
        int n = nums2.length;
      
        int highIndexMedian = (m+n)/2;
        int lowIndexMedian = (m+n)/2-1;
        
        int lowIndexValue = 0;
        int highIndexValue = 0;
        int i = 0;//表示数组nums1的下标
        int j = 0;//表示数组nums2的下标
        int k = 0;//表示计算中位数目前排序到了的顺序下标
        /*计算出可能作为中位数计算的第一个数字*/
        for(; i<m && j<n && k <= lowIndexMedian; k++){
            if(nums1[i]<=nums2[j]){
                lowIndexValue = nums1[i];
                i++;
            }else{
                lowIndexValue = nums2[j];
                j++;
            }
        }
        /*首先分两大类,lowIndexValue的值是否已经找到*/
        if(k > lowIndexMedian){
            if(i>=m){//如果是i越界,剩下的数字就要从nums2中找了
                highIndexValue = nums2[highIndexMedian-m];
             }else if(j>=n){//走到这一步说明是j越界
                highIndexValue = nums1[highIndexMedian-n];
            }else{//说明都没有越界
                
                highIndexValue = nums1[i]<=nums2[j]?nums1[i] : nums2[j];
                
            }
            
        }else{
        
            if(i>=m){//如果是i越界,剩下的数字就要从nums2中找了
                lowIndexValue = nums2[lowIndexMedian-m];
                highIndexValue = nums2[highIndexMedian-m];
            }else if(j>=n){//走到这一步说明是j越界
                lowIndexValue = nums1[lowIndexMedian-n];
                highIndexValue = nums1[highIndexMedian-n];
            }
        }
        
        
         if((m+n)%2 == 0){//如果m+n为偶数,则中位数需要两个中间的数字
            return (lowIndexValue+highIndexValue)/2.0;
        }else{
            return highIndexValue*1.0;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值