题解 | #在两个长度相等的排序数组中找到上中位数#
在两个长度相等的排序数组中找到上中位数
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
//或者通过遍历两个数组, 找到中间位置,如果arr1 + arr2是奇数,则中位数在中间位置,否则偶数在两个数里找一个最小的
if(arr1 == null ||arr2 == null || arr1.length != arr2.length){
return 0;
}
int left1 = 0;
int right1 = arr1.length - 1;
int left2 = 0;
int right2 = arr2.length - 1;
int mid1 = 0;
int mid2 = 0;
int jiou = 0;
while(left1 < right1){
mid1 = left1 + (right1 - left1) / 2;
mid2 = left2 + (right2 - left2) / 2;
//是奇数还是偶数 偶数的话
jiou = (right1 - left1 )%2 ==0 ? 0 : 1;
if(arr1[mid1] > arr2[mid2]){
//中位数在右边
right1 = mid1;
left2 = mid2 + jiou;
}else if(arr1[mid1] < arr2[mid2]){
right2 = mid2;
left1 = mid1 +jiou;
}else{
//相等 说明 0..mid1 mid2...right2 都是 一样的数字
return arr1[mid1];
}
}
return Math.min(arr1[left1], arr2[left2]);
}
}