给定一个任意数组,例如:Nums = [-3,5,6,-2]和任意一个目标值例如:target=4,求数组中三个数的和最接近目标值target,并返回这三个数的和 js
时间: 2023-02-18 20:40:09 浏览: 84
找出哪几个数值的和接近目标值
5星 · 资源好评率100%
代码如下:
let Nums = [-3, 5, 6, -2];
let target = 4;
let minDiff = Number.MAX_VALUE;
let result = 0;
for (let i = 0; i < Nums.length; i++) {
for (let j = i + 1; j < Nums.length; j++) {
for (let k = j + 1; k < Nums.length; k++) {
let sum = Nums[i] + Nums[j] + Nums[k];
let diff = Math.abs(sum - target);
if (diff < minDiff) {
minDiff = diff;
result = sum;
}
}
}
}
console.log(result);
阅读全文