【发布时间】:2020-04-27 16:22:27
【问题描述】:
给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。
您可以假设每个输入都只有一个解决方案,并且您不能两次使用相同的元素。
var twoSum = function(nums, target) {
let comp = {};
for(let i =0; i<nums.length; i++){
let match = target - nums[i]
我的问题是,如果删除 comp[match]>=0 并改用 comp[match],为什么我的代码不起作用?
if(comp[match]>=0){
return [comp[match], i]
console.log(comp)
}
else{
comp[nums[i]]= i
}
console.log(comp)
}
};
片段:
var twoSum = function(nums, target) {
let comp = {};
for (let i = 0; i < nums.length; i++) {
let match = target - nums[i]
if (comp[match]) {
return [comp[match], i]
console.log(comp)
} else {
comp[nums[i]] = i
}
console.log(comp)
}
};
twoSum([2, 7, 11, 15], 9)
【问题讨论】:
-
删除
comp[match]>=0是什么意思?你的 if 语句看起来像if()并且你会得到一个语法错误 -
对于它的价值,我在前几天对这个算法here进行了解释,这可能有助于您更深入地了解它是如何工作的?
-
@NickParsons 我的意思是写
if(comp[match])而不是写if(comp[match]>=0) -
是否有负数?
nums是什么?如果comp[match]为负数,if (comp[match])的计算结果将不同于if (comp[match] >= 0)。 -
@Amy 第一个测试用例 #s 是 2,7,11,15,目标是 9
标签: javascript algorithm