Leetcode关于我的代码为什么不起作用的两个总和问题

时间:2020-01-10 01:50:55

标签: javascript algorithm

给出一个整数数组,返回两个数字的索引,以便它们加起来成为一个特定的目标。

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

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)

1 个答案:

答案 0 :(得分: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 >= 0为假)。但是,如果您想让条件更易读,则可以使用:

if(conp[match] !== undefined)