题目要求
解法一:
暴力解法,遍历每一种可能性。从而求出最小差值的组合。
Time: O(n^2) Space: O(1)
代码:
import java.util.*;
// Brute force
class Program {
public static int[] smallestDifference(int[] arrayOne, int[] arrayTwo) {
// Write your code here.
if (arrayOne == null || arrayTwo == null) return new int[] {};
int min = Integer.MAX_VALUE;
int[] res = new int[2];
for (int i = 0; i < arrayOne.length; i++) {
for (int j = 0; j < arrayTwo.length; j++) {
int temp = min;
int diff = Math.abs(Math.abs(arrayOne[i] - arrayTwo[j]));
min = Math.min(diff, min);
if (min != temp) {
res[0] = arrayOne[i];
res[1] = arrayTwo[j];
}
}
}
return res;
}
}
解法二:
先将两数组排序。设置两个指针从头开始遍历两数组,如果差值等于0,记录直接返回。如果小于当前已知的最小值,进行记录,并将二者较小的Index向右移动。
Time: O(nlogn + mlogm) Space: O(1)
代码:
import java.util.*;
class Program {
public static int[] smallestDifference(int[] arrayOne, int[] arrayTwo) {
// Write your code here.
Arrays.sort(arrayOne);
Arrays.sort(arrayTwo);
int oneIdx = 0;
int twoIdx = 0;
int[] res = new int[2];
int min = Integer.MAX_VALUE;
while (oneIdx < arrayOne.length && twoIdx < arrayTwo.length) {
if (arrayOne[oneIdx] == arrayTwo[twoIdx]) {
return new int[] {arrayOne[oneIdx], arrayTwo[twoIdx]};
}
int diff = Math.abs(arrayOne[oneIdx] - arrayTwo[twoIdx]);
if (diff < min) {
min = Math.min(min, diff);
res[0] = arrayOne[oneIdx];
res[1] = arrayTwo[twoIdx];
}
if (arrayOne[oneIdx] < arrayTwo[twoIdx]) {
oneIdx++;
} else {
twoIdx++;
}
}
return res;
}
}