The Smallest Difference

时间:2021-10-07 16:23:31

Given two array of integers(the first array is array A, the second array is arrayB), 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。

分析:

首先sort, 然后用两个指针分别指向两个array的头部,谁小移动谁。

 public class Solution {
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
public int smallestDifference(int[] A, int[] B) {
Arrays.sort(A);
Arrays.sort(B); int pa = ;
int pb = ; int diff = Integer.MAX_VALUE; while (pa < A.length && pb < B.length) {
if (A[pa] < B[pb]) {
diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
pa++;
} else if (A[pa] == B[pb]) {
return ;
} else {
diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
pb++;
}
}
return diff;
}
}