Given of integers (the first array is an array A
, the second array is an array B
), now we were going to find a El Ement in array A which are a[i], and another element in array B which are b[j], so, 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]
, return0。
Analysis:
First sort, and then with two pointers pointing to two arrays of the head, who moves the small one.
1 Public classSolution {2 /**3 * @param A, b:two integer arrays.4 * @return: their smallest difference.5 */6 Public intSmallestdifference (int[] A,int[] B) {7 Arrays.sort (A);8 Arrays.sort (B);9 Ten intPA =0; One intPB =0; A - intdiff =Integer.max_value; - the 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 0; +}Else { Adiff = math.min (diff, Math.Abs (a[pa)-B[PB])); atpb++; - } - } - returndiff; - } -}
The smallest difference