题解 | #在两个长度相等的排序数组中找到上中位数#
在两个长度相等的排序数组中找到上中位数
http://www.nowcoder.com/practice/6fbe70f3a51d44fa9395cfc49694404f
public class Solution {
/**
* find median in two sorted array
* @param arr1 int整型一维数组 the array1
* @param arr2 int整型一维数组 the array2
* @return int整型
*/
public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) {
// write code here
int len = arr1.length;
return findK(arr1,arr2,len);
}
public int findK(int[] arr1,int[] arr2,int k){
int len1 = arr1.length;
int len2 = arr2.length;
int index1 = 0,index2 = 0;
int kv = 0;
while(true){
if(index1 == len1){
return arr2[index2 + k - 1];
}
if(index2 == len2){
return arr1[index1 + k - 1];
}
if(k == 1){
return Math.min(arr1[index1],arr2[index2]);
}
int half = k / 2;
int new1 = Math.min(index1 + half,len1) - 1;
int new2 = Math.min(index2 + half,len2) - 1;
int v1 = arr1[new1],v2 = arr2[new2];
if(v1 <= v2){
k = k - (new1 - index1 + 1);
index1 = new1 + 1;
}else{
k = k - (new2 - index2 + 1);
index2 = new2 + 1;
}
}
}
}