javascript - 二和算法 - 使用查找索引 - 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))
如果您知道如何完成这项工作,我们将不胜感激!
解决方案
您可以循环数组项并尝试找到其补码以获取目标。如果未找到补码,则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]
推荐阅读
- azure - Azure SignalR 服务错误 - 消息速率达到限制
- typescript - 如果隐藏了 TypeScript 中的全局对象,如何访问它?
- android - 清单合并失败。添加并链接 react-native-splash-screen 后
- hive - 允许在配置单元表的字段中使用空值
- corda - 在 3.1 版中使用节点的问题在不同的机器上
- asp.net - VS 切换到设计器视图时 Windows 窗体崩溃
- python - 如何在python的选项中保留换行符?
- javascript - 如何手动触发特定字段的验证?
- ionic-framework - 一旦用户通过扫描机扫描条形码而不使用点击操作,我想调用一个 ionic 3 事件/方法
- c# - 使用 TestServer 处理错误场景