寻找两个已将排好序的一维数组的中位数
方法一:暴力法
将两个数组按照顺序放在已经排好序的新建的数组内,然后取出其中的中位数
public class StudyOne {
public static void main(String[]arg) {
int[] a= {4,5,7,9};
int[] b= {1,3,6,11,13};
findMadianSortedArrays(a,b);
}
public static double findMadianSortedArrays(int[] nums1,int[] nums2) {
int m=nums1.length;
int n=nums2.length;
int[] nums=new int[m+n];
if(m==0) {
if(n%2==0) {
return(nums2[n/2-1]+nums2[n/2])/2;
}else {
return(nums2[n/2]);
}
}
if(n==0) {
if(m%2==0) {
return(nums2[m/2-1]+nums2[m/2])/2;
}else {
return(nums2[m/2]);
}
}
int count=0;
int i=0,j=0;
while(count!=(m+n)) {
if(i==m) {
while(j!=n) {
nums[count++]=nums2[j++];
}
break;
}
if(j==n) {
while(i!=m) {
nums[count++]=nums2[i++];
}
break;
}
if(nums1[i]<nums2[j]) {
nums[count++]=nums1[i++];
}else {
nums[count++]=nums2[j++];
}
}
if(count%2==0) {
System.out.println((nums[count/2-1]+nums[count/2])/2);
return(nums[count/2-1]+nums[count/2])/2;
}else {
System.out.println(nums[count/2]);
return nums[count/2];
}
}
}
方法二:
public class StudyOne {
public static void main(String[]arg) {
int[] a= {4,5,7,9};
int[] b= {1,3,6,11,13};
findMadianSortedArrays(a,b);
}
public static double findMadianSortedArrays(int[] A,int[]B) {
int m=A.length;
int n=B.length;
int len=m+n;
int left=-1,right=-1;
int aStart=0,bStart=0;
for(int i=0;i<=len/2;i++) {
left=right;
if(aStart<m &&(bStart>=n||A[aStart]<B[bStart])){
right=A[aStart++];
}else {
right=B[bStart++];
}
}
if(len%2==0) {
System.out.println((left+right)/2.0);
return(left+right)/2.0;
}else {
System.out.println(right);
return right;
}
}
}