简体   繁体   中英

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).

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

Output [1,2]

Expected [2,3]

I would propose a simpler approach (see below) that eliminates the need for your filter/indexOf line. 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]

Overall I don't think the.indexOf() method is working the way you think it is.

sum = [ 1, 1, 2, 3, 3, 2 ] just before you filter it (indexes = 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. So in your case the first element (1 with index 0) is being included in your final solution -> [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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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