最小差

给定两个整数数组 a 和 b,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差

  • 输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
    输出:3,即数值对(11, 8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var smallestDifference = function (a, b) {
const compare = (x, y) => x - y;
a.sort(compare);
b.sort(compare);
let m = a.length, n = b.length, i = 0, j = 0;
let ans = Infinity;
while (i < m && j < n) {
let x = a[i], y = b[j], delta = Math.abs(x - y);
ans = Math.min(ans, delta);
if (x > y) j++;
else i++;
}
return ans;
}