题目
There are two sorted arrays A and B of size m and nrespectively. Find the median of the two sorted arrays.
Example
Given A=[1,2,3,4,5,6]
and B=[2,3,4,5]
, the median is 3.5
.
Given A=[1,2,3]
and B=[4,5]
, the median is 3
.
Challenge
The overall run time complexity should be O(log (m+n))
.
分析
(1)每次至多可以确定 k/2 个元素不会是第 K 个元素
(2)TC = lgk,k 初始为 lg(m+n)
代码
public class Solution {
/*
* @param A: An integer array
* @param B: An integer array
* @return: a double whose format is *.5 or *.0
*/
public double findMedianSortedArrays(int[] A, int[] B) {
int an = A.length;
int bn = B.length;
int n = an+bn;
if(n%2==0){//全数组和为偶数
return (findKth(A,B,n/2)+findKth(A,B,n/2+1))/2.0;
}else{
return findKth(A,B,n/2+1);
}
}
public int findKth(int[] A, int[] B, int k){
int an = A.length;
int bn = B.length;
if(an>bn) return findKth(B,A,k);//总是使得第一个参数数组小于第二个
if(an==0) return B[k-1];//A中的已经被排除干净了,直接取B中剩下的位数
if(k==1) return Math.min(A[0], B[0]);//取两者中最小的,就是目标K
int aIndex = Math.min(an, k/2);
int bIndex = Math.min(bn, k/2);
if(A[aIndex-1] > B[bIndex-1]){//可以确定,B中bIndex个不是第k元素
return findKth(A, Arrays.copyOfRange(B, bIndex, bn), k-bIndex);
}else{
return findKth(Arrays.copyOfRange(A, bIndex, an), B, k-aIndex);
}
}
}