JavaScript 查找数组中和最接近目标值的子数组
JavaScript 查找数组中和最接近目标值的子数组
问题: 给定一个数字 target 和一个数组 b,找出 b 中哪一段之和与 target 最接近,并返回该子数组。
思路:
- 初始化两个变量:
closest表示当前最接近的和,result表示对应的数组段。 - 遍历数组
b,从每个元素开始计算到数组末尾的和,同时比较当前和与target的差值是否比当前最接近的差值更小,如果更小则更新closest和result。 - 最后返回
result。
代码实现:
function findClosestSum(target, b) {
let closest = Infinity;
let result = [];
for (let i = 0; i < b.length; i++) {
let sum = 0;
for (let j = i; j < b.length; j++) {
sum += b[j];
if (Math.abs(sum - target) < Math.abs(closest - target)) {
closest = sum;
result = b.slice(i, j + 1);
}
}
}
return result;
}
解释:
该函数接受两个参数:目标数字 target 和数组 b,返回 b 中哪一段之和最接近 target。
函数首先初始化两个变量 closest 和 result,分别用来存储当前最接近的和以及对应的子数组。
然后,函数遍历数组 b,从每个元素开始计算到数组末尾的和。对于每个子数组,函数计算其和与 target 的差值,并与 closest 进行比较。如果当前差值小于 closest,则更新 closest 和 result。
最后,函数返回 result,即为 b 中哪一段之和最接近 target。
示例:
let target = 10;
let b = [1, 2, 3, 4, 5];
let result = findClosestSum(target, b);
console.log(result); // [3, 4, 5]
在这个例子中,b 中子数组 [3, 4, 5] 的和为 12,与 target 10 最接近,因此函数返回该子数组。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ncRw 著作权归作者所有。请勿转载和采集!