题解 | #在两个长度相等的排序数组中找到上中位数#
在两个长度相等的排序数组中找到上中位数
http://www.nowcoder.com/practice/6fbe70f3a51d44fa9395cfc49694404f
来自第三方平平台的答案
public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) { // write code here int len1 = arr1.length, len2 = arr2.length; int k = (len1+len2+1)/2; return getMid(arr1, 0, len1-1, arr2, 0, len2-1, k); } // 求出arr1和arr2中第k小的数 int getMid(int[] arr1, int start1, int end1, int[] arr2, int start2, int end2, int k){ int len1 = end1-start1+1, len2 = end2-start2+1; if (len1 > len2) return getMid(arr2, start2, end2, arr1, start1, end1, k); if (len1 == 0) return arr2[start2+k-1]; if (k == 1) return Math.min(arr1[start1], arr2[start2]); int i = start1+Math.min(len1, k/2)-1; int j = start2+Math.min(len2, k/2)-1; if (arr1[i] > arr2[j]){ return getMid(arr1, start1, end1, arr2, j+1, end2, k-(j-start2+1)); }else{ return getMid(arr1, i+1, end1, arr2, start2, end2, k-(i-start1+1)); } }