给定两个大小为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:那个进阶的好难。。。。想吃饭了,所以就。。。。。。