这是解决此问题的最佳和最快的解决方案:
找到A和B之间的最短距离,A和B在一个数组中有数组中的值列表,如[4,8,9,10,100],我们需要找出它们之间的最小差距该数组中的两个值。如果它是否定的则使用绝对值。
答案 0 :(得分:1)
function closetPairs (arr) {
let result = [];
let minDiff = Number.MAX_VALUE;
arr.sort((a, b) => {
return a - b;
});
// find the lowest difference for a pair of elements in the sorted array
for (let i = 0; i < arr.length - 1; i++) {
let currDiff = arr[i + 1] - arr[i];
if (currDiff < minDiff) {
minDiff = currDiff;
}
}
// find all the pairs with lowest differnece
for (let j = 0; j < arr.length - 1; j++) {
let sortedEleDiff = arr[j + 1] - arr[j];
if (minDiff == sortedEleDiff) {
result.push(arr[j + 1], arr[j]);
}
}
return result.sort((a, b) => {
return a - b;
});
}
let inputArr = [4, 8, 9, 10, 100];
console.log(closetPairs(inputArr)); // [ 8, 9, 9, 10 ]