在 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