简体   繁体   English

二和 Leetcode

[英]Two Sum Leetcode

I wrote the code, but for some reason it displays the index 1, 2, 3, while 3 + 4 will in no way be equal to target (6).我编写了代码,但由于某种原因,它显示了索引 1、2、3,而 3 + 4 绝不会等于目标 (6)。

var twoSum = function(nums, target) {
   let sum = [];
   var n = 2;

    for(let i = 0; i < nums.length; i++) {
       for(let a = 1; a < nums.length; a++) {
           if(nums[i] + nums[a] == target) {
               sum.push(i);
               sum.push(a);
           }
       }
   } 
   let unique = sum.filter((e, i) => sum.indexOf(e) === i )
   return unique/* .slice(0, n); */
};
console.log(twoSum([1,3,4,2],6))

Input [1,3,4,2] 6输入 [1,3,4,2] 6

Output [1,2] Output [1,2]

Expected [2,3]预计 [2,3]

I would propose a simpler approach (see below) that eliminates the need for your filter/indexOf line.我会提出一种更简单的方法(见下文),它消除了对 filter/indexOf 行的需要。 This just takes care of comparing indexes in one line, a bit more succinct.这只是在一行中比较索引,更简洁一点。

As well, when I ran your code the actual output was [1, 2, 3] not [1, 2]同样,当我运行您的代码时,实际的 output 是 [1, 2, 3] 而不是 [1, 2]

Overall I don't think the.indexOf() method is working the way you think it is.总的来说,我认为 .indexOf() 方法并没有像你想象的那样工作。

sum = [ 1, 1, 2, 3, 3, 2 ] just before you filter it (indexes = 0, 1, 2, 3, 4, 5) sum = [ 1, 1, 2, 3, 3, 2 ] 在过滤之前(索引 = 0, 1, 2, 3, 4, 5)

Inside the filter:过滤器内部:

sum.indexOf(1) -> 0 === the current index 0  (Yes so we include it in the unique array)
sum.indexOf(1) -> 0 === the current index 1 
...

.indexOf() defaults to the first existence of an element in the array. .indexOf() 默认为数组中第一个存在的元素。 So in your case the first element (1 with index 0) is being included in your final solution -> [1, 2, 3].因此,在您的情况下,第一个元素(索引为 0 的 1)包含在您的最终解决方案中 -> [1, 2, 3]。

Hope that explains your results a bit, good luck with tweaking your code!希望能稍微解释一下你的结果,祝你修改代码好运!

 var twoSum = function(nums, target) { for (let i = 0; i < nums.length; i++) { for (let j = 0; j < nums.length; j++) { if (nums[i] + nums[j] === target && i,== j) return [i; j]; } } // You may need this to cover an edge case for a leetCode style question return [] }. console,log(twoSum([1,3,4,2],6))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM