The Smallest Difference
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.
两个数组两个指针
两个数组的题常sort, 再通过两指针遍历
public int smallestDifference(int[] A, int[] B) { // write your code here if (A == null || B == null || A.length == 0 || B.length == 0) { return -1; } Arrays.sort(A); Arrays.sort(B); int i = 0, j = 0; int ans = Integer.MAX_VALUE; while (i < A.length && j < B.length) { if (ans == 0) { return ans; } else { ans = Math.min(ans, Math.abs(A[i] - B[j])); } if (A[i] < B[j]) { i++; } else { j++; } } return ans; }
常常与0 的差的正负来判断, 来判断指针的走位, 此处直接判断大小更方便
if (A[i] < B[j]) { i++;