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)).Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
题目描述
寻找两个数组的中位树
思路
这道题一开始没有想出来,从网上看的题解,领略到了递归的牛X之处。简单来说就是,每一次查找来缩小一半的范围。直到一个数组为0时,即可通过下标找到该值。
public class MedianOfTwoList {
int lena = 0 ;
int lenb = 0;
public double findMedianSortedArrays(int A[], int B[]) {
lena = A.length;
lenb = B.length;
int sum = lena+lenb;
if ( sum%2==1 ) {
return getKthNumber(A, 0, B, 0, sum/2+1)*1.0;
} else {
float s = getKthNumber(A, 0, B, 0, sum/2);
lena = A.length;
lenb = B.length;
float s2 = getKthNumber(A, 0, B, 0, sum/2+1) ;
return (s+s2)/2.0;
}
}
private int getKthNumber(int[] a,int sa,int[] b,int sb,int k) {
if ( this.lena-sa >this.lenb-sb ) {
int temp = this.lena;
this.lena = this.lenb;
this.lenb = temp;
return getKthNumber(b, sb, a, sa, k);
}
else {
if ( this.lena-sa==0 ) {
return b[sb+k-1];
} else {
int m = Integer.min(k/2, this.lena-sa);
if ( m==0 ) {
return a[sa]<b[sb]?a[sa]:b[sb];
} else {
if ( a[sa+m-1]<b[sb+m-1] ) {
return getKthNumber(a, sa+m, b, sb, k-m);
} else {
return getKthNumber(a, sa, b, sb+m, k-m);
}
}
}
}
}
}