📅  最后修改于: 2023-12-03 15:37:35.674000             🧑  作者: Mango
有时候我们需要在一个数组中查找最接近特定数字的数字。在javascript中,我们可以使用一些函数和算法来实现这个功能。
最简单的方法是遍历整个数组,并计算每个数字与目标数字之间的差距。我们可以将这个差距保存到一个数组中。然后,我们可以使用Math.min()函数找到数组中最小的差距,从而找到最接近目标数字的数字。
function findClosestNumber(target, numbersArray) {
let closest = null;
let closestDiff = Number.MAX_VALUE; // 最大值
for (let i = 0; i < numbersArray.length; i++) {
let difference = Math.abs(target - numbersArray[i]);
if (difference < closestDiff) {
closest = numbersArray[i];
closestDiff = difference;
}
}
return closest;
}
let numbers = [4, 7, 11, 16, 22, 25];
let targetNumber = 14;
let closestNumber = findClosestNumber(targetNumber, numbers);
console.log("Closest Number: " + closestNumber);
输出结果:
Closest Number: 16
二分查找是一种更有效的算法,它可以更快地找到最接近目标数字的数字。二分查找需要将数组排过序。
function findClosestNumber(target, numbersArray) {
let min = 0;
let max = numbersArray.length - 1;
let mid;
let closest = null;
let closestDiff = Number.MAX_VALUE;
while (min <= max) {
mid = Math.floor((min + max) / 2);
let currentNum = numbersArray[mid];
let difference = Math.abs(target - currentNum);
if (difference < closestDiff) {
closest = currentNum;
closestDiff = difference;
}
if (currentNum < target) {
min = mid + 1;
} else {
max = mid - 1;
}
}
return closest;
}
let numbers = [4, 7, 11, 16, 22, 25];
let targetNumber = 14;
let closestNumber = findClosestNumber(targetNumber, numbers);
console.log("Closest Number: " + closestNumber);
输出结果:
Closest Number: 16
本文介绍了在javascript中查找最接近特定数字的数字的两种方法:遍历数组查找和采用二分查找。二分查找比遍历数组查找更快,但需要将数组排过序。具体使用哪种方法取决于具体情况。