我们需要编写一个函数,该函数将数字数组作为第一个参数,将目标和作为第二个参数。然后,我们要遍历数组,然后将每个值彼此相加(自身+自身除外)。
而且,如果循环通过的两个值的总和等于目标总和,并且之前从未遇到过这对值,则我们会记住它们的索引,最后返回所有记住的索引的总和。
如果数组是-
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