The Smallest Difference
Source
Given two array of integers(the first array is array A, the second array is
array B), now we are going to find a element in array A which is A[i], and another
element in array B which is B[j], so that the difference between A[i] and
B[j] (|A[i] - B[j]|) is as small as possible, return their smallest difference.
Example
For example, given array A = [3,6,7,4], B = [2,8,9,3], return 0
Challenge
O(n log n) time
Java
public class Solution {
public int smallestDifference(int[] A, int[] B) {
Arrays.sort(A);
Arrays.sort(B);
int a=0;
int b=0;
int min_num=Integer.MAX_VALUE;
while(a<A.length && b<B.length){
int num = Math.abs(A[a]-B[b]);
min_num = Math.min(min_num, num);
if(A[a]<B[b]){
a++;
}
else{
b++;
}
}
return min_num;
}
}