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

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

进阶:你能设计一个时间复杂度为o(log(m+n))的算法解决此问题吗?

实例:

输入:num1 = [1,3],num2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3],中位数 2

方法一:利用import org.apache.commons.lang3.ArrayUtils 来合并数组 ; java.util.Arrays.sort();来将数组中的数值排序

代码

import org.apache.commons.lang3.ArrayUtils;//要提前导入jar文件
import java.util.Arrays;

public class test {
    public static void main(String[]args)
    {
        int[]a={1,2,3};
        int[]b={4,5,6};
        System.out.print("中位数为:"+ave(a,b));
    }

    public static int ave(int [] num1,int [] num2)
    {
        int [] both = (int []) ArrayUtils.addAll(num1,num2);//将两个数组合并
        java.util.Arrays.sort(both);//自动排序
        int median = both[both.length/2];
        return median;
    }


}

注意:这个方法在我的编译器上运行失败了,说是什么版本不支持。。。

方法二:利用java中的数组复制,将两个数组复制到同一个数组中去,然后使用Arrays.sort();自动将数组从小到大排列起来

代码

import java.util.Arrays;

public class test {
    public static void main(String[]args)
    {
        int[]a={1,2,3};
        int[]b={4,5,6};
        System.out.print("中位数为:"+ave(a,b));
    }

    public static double ave(int [] num1,int [] num2)
    {
        int[] both = new int[num1.length+num2.length];
        System.arraycopy(num1,0,both,0,num1.length);
        System.arraycopy(num2,0,both,num1.length,num2.length);
        java.util.Arrays.sort(both);
        double sum=0;
        double ave;
        for(int x:both)
        {
            sum+=x;
        }
        ave = sum/both.length;
        return ave;



    }


}

ps:那个进阶的好难。。。。想吃饭了,所以就。。。。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值