这道题确实有点难,想挺久,看别人答案也是不能一下子就明白。题目难度为Hard,原题如下:
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)).
给定两个已排序的数组,求两个数组整体的中位数。时间复杂度要求为O(log
(m+n))。
一、思路:
将本体求中位数的要求调整为将两个数组整体合并排序后求其第k个数。下面用一个例子来说明:
图一、例子示意图
A班和B班的同学人数分别为aEnd与bEnd,有天体育老师说要找他们中间第k矮的同学,于是先将两班的同学按从小到大的顺序站成两队。假设k是为13。那此时A班派出第x矮的同学,B班派出第y矮的同学来比较(注意:此时x+y<=k)。
若x为6,y为7。如果A的第6位同学比B的第7位同学还要矮,那如果两班整体排序,那A班的6位同学一定是要站在B班的第7位前面,最多A班第6位就站在B班第7位的前一位,最多就整体排第12,怎么都轮不到他排第k=13个。于是可以把A班前6位丢掉,在剩下的两个队列里面找。但是就不再是找第k个,而是找第k-x个了。因为x做了基数被丢掉了。
当然,上述例子,只要(x+y)<=k的情况,x与y只要是为非负的,那都可以。只是为了效率,一般去x=y=(k/2)。而当某一队被丢到剩下人很少或者没人了,那这个取值就要根据具体情况来取值。
二、java 程序:
public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; int k = m + n; if((k&1)==1) { return find(nums1, 0, m, nums2, 0, n, k/2+1); }else return (find(nums1, 0, m, nums2, 0, n, k/2)+find(nums1, 0, m, nums2, 0, n, k/2+1))/2; } //递归算法,不断缩小两个数组的范围,同时k的值也相对两个搜索区间上限起始点而改变 public double find(int[] A, int aStart, int aEnd, int[] B, int bStart, int bEnd,int kth) { //1. 统一将长度短的放置于find函数参数的前面项 if(aEnd>bEnd) return find(B, bStart, bEnd, A, aStart, aEnd, kth); //2. 长度短的为空,则答案等同于求另外一个数组的中位数 if(aEnd<=0) return B[bStart + kth -1]; //3. 递归到终点,两个数组的aStart和bStart已经到了中位数的位置 if(kth==1) return min(A[aStart],B[bStart]); int pa = min(kth/2,aEnd), pb = kth-pa; if(A[aStart + pa-1]< B[bStart +pb -1]) return find(A, aStart+pa, aEnd-pa, B, bStart, bEnd, kth-pa ); else return find(A, aStart, aEnd, B, bStart + pb, bEnd - pb,kth-pb); } public int min(int a, int b) { return a>b?b:a; } }
参考:LeetCode
– Median of Two Sorted Arrays Java
Median
of Two Sorted Arrays (JAVA)