在 JavaScript 中查找所有唯一数字对的索引总和的最小值,这些数字对的和等于给定的数字
我们需要编写一个函数,该函数将数字数组作为第一个参数,目标和作为第二个参数。然后,我们希望遍历数组,并将每个值加到其他值(除了自身加自身)。
如果遍历的两个值的和等于目标和,并且之前没有遇到过这对值,那么我们会记住它们的索引,最后返回所有记住的索引的总和。
如果数组是 -
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP