在 JavaScript 中查找所有唯一数字对的索引之和的最小值,这些数字对的总和等于给定数字
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个函数,该函数将数字数组作为第一个参数,将目标和作为第二个参数。然后,我们要循环遍历该数组,然后将每个值相加(除了它本身 + 它本身)。
如果循环遍历的两个值的总和等于目标和,并且该对值之前没有遇到过,那么我们会记住它们的索引,最后返回所有记住的索引的总和。
如果数组为 −
const arr = [1, 4, 2, 3, 0, 5];
并且总和为 −
const sum = 7;
那么输出应该是 11,因为,
4 + 3 = 7 5 + 2 = 7
索引 −
4 [index: 1] 2 [index: 2] 3 [index: 3] 5 [index: 5]
即
1 + 2 + 3 + 5 = 11
示例
其代码为 −
const arr = [1, 4, 2, 3, 0, 5];
const findIndexSum = (arr = [], sum = 0) => {
let copy = arr.slice(0);
const used = [];
let index = 0, indexFirst = 0, indexSecond, first, second;
while (indexFirst < copy.length){
indexSecond = indexFirst + 1;
while(indexSecond < copy.length){
first = copy[indexFirst];
second = copy[indexSecond];
if (first + second === sum){
used.push(first, second);
copy = copy.filter(el => first !== el && second !== el );
indexFirst--;
break;
}
indexSecond++;
}
indexFirst++;
};
const indexSum = used.sort().reduce((acc, val, ind) => {
const fromIndex = ind === 0 || val !== used[ind - 1] ? 0 : index + 1 index = arr.indexOf(val, fromIndex);
return acc + index;
}, 0);
return indexSum;
};
console.log(findIndexSum(arr, 7));
输出
控制台中的输出将是 −
11
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

