Javascript 中的两个 Sum Leetcode - 代码看起来正确但 Leetcode 说它是错误的

Age*_*bra 0 javascript

我正在研究Leetcode 中“Two Sum”问题

我确定这段代码是正确的,我已经在 Repl 中测试过它并且在那里看起来是正确的,但是 Leetcode 给了我一个错误。

这是我的代码:

var arr = [];

var twoSum = function(nums, target) {
   for(var i = 0; i < nums.length; i++){
        for(var j = i+1; j < nums.length; j++){
            console.log(nums[i] + ', ' + nums[j]);
            var tot = nums[i] + nums[j];        
            if(tot === target){
                arr.push(i,j);
                console.log(arr);
                return arr;
            }     
         }         
   }
};

//var a = [2, 7, 11, 15];
//var b = 9;
var a = [2, 3, 4];
var b = 6;

twoSum(a, b);
Run Code Online (Sandbox Code Playgroud)

我得到的错误如下:

Input:
[3,2,4]
6
Output:
[0,1,1,2]
Expected:
[1,2]
Run Code Online (Sandbox Code Playgroud)

为什么期待[1, 2][0, 1]在这种情况下当然应该期待,然后为什么我的代码两次添加到 arr 数组?对我来说这看起来像是一个错误......

注意:我看到 Leetcode 上有很多关于这个问题的帖子,但没有一个解决我在 Javascript 中遇到的具体问题。

Tim*_*lla 5

为什么它期待 [1, 2]?

因为 2 + 4 = 6

在这种情况下,它当然应该期望 [0, 1]

不,因为 3 + 2 = 5

然后为什么我的代码两次添加到 arr 数组?

因为您在函数外部声明了数组。每次调用该函数时都会重新使用它。将数组声明移动到您的twoSum函数中,甚至更好:只需return [i, j]将其push放入空数组中即可。