# 快手算法面试题：求从两个有序数组选出两个数，能得出的最小差值，取绝对值

/**
* 快手算法面试题：
* 求从两个有序选出两个数，能得出的最小差值，取绝对值
* 知识点：变种二分法，寻找边界
* 时间复杂度：O(nlogn)
*/
public class Main {
public static void main(String[] args) {
int[] arr1 = {1,2,676};
int[] arr2 = {3,5,7};
System.out.println(new Main().fun(arr1, arr2));
}

public int fun(int[] a,int[] b){
int res = -1;
for(int i = 0; i < a.length;i++){
if(b[b.length / 2] > a[i]){
int leftBound = leftSearch(b,a[i]);
int newRes = Math.abs(a[i] - b[leftBound]);
if(newRes != 0){
if( res != -1){
res = Math.min(newRes,res);
}else{
res = newRes;
}
} else{
return res = 0;
}
} else if(b[b.length / 2] < a[i]){
int rightBound = rightSearch(b,a[i]);
int newRes = Math.abs(a[i] - b[rightBound]);
if(newRes != 0){
if( res != -1){
res = Math.min(newRes,res);
}else{
res = newRes;
}
} else{
return res = 0;
}
} else{
return res = 0;
}
}
System.out.println(res);
return res;
}

public int leftSearch(int[] arr,int target){
int left = 0;
int right = arr.length - 1;
while(left <= right){
int mid = left + (right - left)/2;
if(arr[mid] > target){
right = mid - 1;
} else if( arr[mid] < target){
if(target  - arr[mid]  > arr[mid + 1] - target){
return mid + 1;
}
return mid;
} else{
return mid;
}
}
return left;
}

public int rightSearch(int[] arr,int target){
int left = 0;
int right = arr.length - 1;
while(left <= right){
int mid = left + (right - left) / 2;
if(arr[mid] < target){
left = mid + 1;
} else if(arr[mid] > target ){
if( arr[mid] - target >  target - arr[mid - 1]){
return mid - 1;
}
return mid;
} else{
return mid;
}
}
return right;
}


06-25 1268
05-28 3109

05-06 1万+
11-30 4899
04-11 205
07-13 281
04-05 1438
02-01 3238
05-15 4741
04-27 1415
01-22 1428
10-29 47
08-23 1万+
03-20 83
03-20 4215