leetcode-Median of Two Sorted Arrays

leetcode-Median of Two Sorted Arrays

题目:

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.
主要意思是:有两个有序的数组,要找到这两个数组中的中位数。

思路:

这里有三个点需要着重注意:

  • 两个数组都是有序的
  • 两个数组中,可能其中一个是空值(考虑边界问题)
    在遍历数组的过程中,要将下标的检查放在最前面,防止一开始就出现有数组为空而越界的情况
  • 要求算法的平均复杂度是log(m+n)
    数组的有序,为平均复杂度提供了可能,因此要充分理由有序的优势。为了降低复杂度,可以使用加大空间复杂度的方式。这道题目的主要思路是借助了如何将两个有序数组并称一个有序数组的思路

代码:

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int s1_length=nums1.length;
        int s2_length=nums2.length;
        int low=0;
        int high=s1_length+s2_length-1;
        int s1_low=0;
        int s1_high=s1_length-1;
        int s2_low=0;
        int s2_high=s2_length-1;
        int[] num_res=new int[s1_length+s2_length];
        while(low<=high){

            //考虑某个数组越界了之后的情况
            if(s1_low>s1_high||s2_low>s2_high){
                break;
            }
            //找到放入low中的值
            if(nums1[s1_low]<nums2[s2_low]){
                num_res[low++]=nums1[s1_low];
                s1_low++;
            }
            else{
                num_res[low++]=nums2[s2_low];
                s2_low++;

            }

            //找到放入high中的值
            if(nums1[s1_high]>nums2[s2_high]){
                num_res[high--]=nums1[s1_high];
                s1_high--;
            }
            else{
                num_res[high--]=nums2[s2_high];
                s2_high--;
            }


        }
        //处理如果两个数组中的一个数组提前被访问完
        while(s1_low<=s1_high){
            num_res[low++]=nums1[s1_low++];
        }
        while(s2_low<=s2_high){
            num_res[low++]=nums2[s2_low++];
        }

        if((s1_length+s2_length)%2==0){
            int mid=(s1_length+s2_length)/2;
            return ((num_res[mid]+num_res[mid-1])/2.0);
        }
        else{
            int mid=(s1_length+s2_length)/2;
            return (num_res[mid]);
        }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值