【问题标题】:Leetcode Two sum problem question about why my code doesn't workLeetcode 关于为什么我的代码不起作用的两个和问题
【发布时间】: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]&gt;=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]&gt;=0 是什么意思?你的 if 语句看起来像 if() 并且你会得到一个语法错误
  • 对于它的价值,我在前几天对这个算法here进行了解释,这可能有助于您更深入地了解它是如何工作的?
  • @NickParsons 我的意思是写if(comp[match])而不是写if(comp[match]&gt;=0)
  • 是否有负数? nums 是什么?如果comp[match] 为负数,if (comp[match]) 的计算结果将不同于 if (comp[match] &gt;= 0)
  • @Amy 第一个测试用例 #s 是 2,7,11,15,目标是 9

标签: javascript algorithm


【解决方案1】:

comp 背后的想法是存储您在循环遍历数字数组时之前看到的值的索引。这意味着对象中的键可以指向索引0

在 JavaScript 中,0 被认为是 falsy,因此当放入 if 语句时,它将跳过 if 块,因为它被认为是 false,而是执行 else 块.

if(0) {
  console.log("truthy"); // doesn't execute
} else {
  console.log("falsy");
}

因此,如果您要使用 if(comp[match])comp[match] 为您提供 0 的索引值,则您的 else 块将触发,而您实际上需要您的 if 块来触发(正如您之前看到的一个数字,您现在可以将其与当前数字相加)。这就是为什么以下内容按预期工作的原因:

if(comp[match] >= 0)

在这种情况下,如果comp[match] 返回0 的索引值,您的 if 块中的代码将根据需要触发。 comp[match] 有可能返回 undefined。在这种情况下,您的 else 块将触发,因此您的代码将正常工作(因为 undefined &gt;= 0 为假)。但是,如果您想让您的条件更具可读性,您可以改用:

if(conp[match] !== undefined)

【讨论】:

  • 谢谢,我忘了零可能是错误的索引。如果你不介意扩展。我们什么时候可以得到不确定的情况?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多