首页 > 解决方案 > 二和算法 - 使用查找索引 - Javascript 算法

问题描述

问题

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

您可能会假设每个输入都只有一个解决方案,并且您可能不会两次使用相同的元素。

但是,我特别想使用 findIndex() 来解决这个问题。问题是我们需要将两个索引相加!不止一个。

function twoSum(arr, target){

let relevantArr = [];

let newArr = arr.slice(0,);

function test(){

return newArr.findIndex(added);

}

function added (a, b) {
  a + b == target;

}


return relevantArr
}



console.log(twoSum([2, 7, 11, 15], 9))

如果您知道如何完成这项工作,我们将不胜感激!

标签: javascriptalgorithm

解决方案


您可以循环数组项并尝试找到其补码以获取目标。如果未找到补码,则findIndex返回 -1 并检查下一个。

function twoSum(arr, target){
    for(let i = 0, len = arr.length ; i < len ; ++i)
    {
        // try to find an item so that its sum with arr[i] is equal to the target
        let j = arr.findIndex(item => item + arr[i] == target); 
        if(j != -1)
        {
            // we found the element, we can return the answer
            return [i, j];
        }
    }
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0,1]
console.log(twoSum([2, 7, 11, 15], 18)); // [1,2]

推荐阅读