LeetCode 寻找两个正序数组的中位数 题解

一、题目

1、原题链接

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

2、题目详情

  给定两个大小分别为 m m m n n n 的正序(从小到大)数组 nums1nums2。请你找出并返回这两个正序数组的 中位数。

二、解题思路

  (1)本题需要我们找到两个正序数组的中位数,则需要我们把两个数组合并之后才能再找到数组,那么我们要怎么合并这两个数组呢?
   j a v a java java中我们可以重新写一个合并两个数组数组的函数,代码如下:

    static int[] concat(int[] a, int[] b) {
       int[] c= new int[a.length+b.length];
       System.arraycopy(a, 0, c, 0, a.length);
       System.arraycopy(b, 0, c, a.length, b.length);
       return c;
    }

  代码使用了 j a v a java java库中的 a r r a y c o p y arraycopy arraycopy函数来实现。
  (2)合并完两个数组之后,我们发现合并后的数组并不是一个递增的数组,所以我们需要对合并后数组进行排序, j a v a java java中有 A r r a y s . s o r t ( ) Arrays.sort() Arrays.sort()函数可以将数组排序。
  (3)将数组排完序后,即可分数组长度的奇偶来找到中位数。

三、代码

class Solution {
    static int[] concat(int[] a, int[] b) {
       int[] c= new int[a.length+b.length];
       System.arraycopy(a, 0, c, 0, a.length);
       System.arraycopy(b, 0, c, a.length, b.length);
       return c;
    }
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;
        int[] ret =new int [m+n];
        ret = concat(nums1,nums2);
        Arrays.sort(ret);
        double ans =0;
        if((m+n)%2==0){
            ans = (ret[(m+n)/2]+ret[(m+n)/2-1])/2.0;
        }
        else{
            ans = ret[(int)(m+n)/2];
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

枏念

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

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

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

打赏作者

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

抵扣说明:

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

余额充值