我正在研究 Leetcode 中的“二和”问题。
我确信这段代码是正确的,我已经在 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);
我收到的错误如下:
Input:
[3,2,4]
6
Output:
[0,1,1,2]
Expected:
[1,2]
为什么期待
[1, 2]
?当然,在这种情况下应该期望 [0, 1]
,那么为什么我的代码会两次添加到 arr 数组呢? 对我来说这看起来像是一个错误...
注意:我看到 Leetcode 上有很多关于这个问题的帖子,但没有一个帖子解决了我在 Javascript 中遇到的具体问题。
为什么期待 [1, 2]?
因为 2 + 4 = 6
在这种情况下当然应该期望 [0, 1]
不,因为 3 + 2 = 5
那么为什么我的代码两次添加到 arr 数组?
因为您在函数外部声明了数组。每次调用该函数时都会重复使用它。将数组声明移动到您的
twoSum
函数中,甚至更好:只需 return [i, j]
而不是 push
进入空数组。
这是您可以尝试的另一种解决方案...
var twoSum = function(nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
let compliment = target - nums[i];
if (map[compliment]) {
return [(map[compliment] - 1), i];
} else {
map[nums[i]] = i + 1;
}
}
};
twoSum([2, 3, 4],6);
这是一个最佳解决方案
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
function twoSum(nums, target) {
const numsObjs = {}; // create nums obj with value as key and index as value eg: [2,7,11,15] => {2: 0, 7: 1, 11: 2, 15: 3}
for (let i = 0; i < nums.length; i++) {
const currentValue = nums[i];
if (target - currentValue in numsObjs) {
return [i, numsObjs[target - currentValue]];
}
numsObjs[nums[i]] = i;
}
return [-1, -1];
}
console.log(twoSum([2, 7, 11, 15], 9))
这是我的解决方案,这是一种暴力方法,使用javascript来搜索所有可能的数字对。
var twoSum = function(nums, target) {
let numarray = new Array(2);
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
numarray[0] = i;
numarray[1] = j;
}
}
}
return numarray;
};
我很久以前就解决了这个问题。希望这对您有帮助!
class Solution {
twoSum(nums, target) {
const n = nums.length;
let ans = [];
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (nums[i] + nums[j] === target) {
ans.push(i);
ans.push(j);
return ans;
}
}
}
return ans;
}