给定两个整数数组(第一个是数组 A
,第二个是数组 B
),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。
样例
给定数组 A = [3,4,6,7]
, B = [2,3,8,9]
,返回 0
。
挑战
时间复杂度 O(n log n)
public class Solution {
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
public int smallestDifference(int[] A, int[] B) {
// write your code here
Arrays.sort(A);
Arrays.sort(B);
int left=0;
int right=B.length-1;
int smallest=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++){
while(left<right&&B[left]<A[i]){
left++;
}
if(left==0){
smallest=Math.min(smallest,Math.abs(B[left]-A[i]));
}else{
smallest=Math.min(smallest, Math.min(Math.abs(B[left-1]-A[i]), Math.abs(B[left]-A[i])));
}
}
return smallest;
}
}