https://leetcode.com/problems/two-sum/
var twoSum = function(nums, target) {
let result = [0, 0];
for (let i = 0; i < nums.length; i++) {
const rest = target - nums[i];
let restIndex = nums.indexOf(rest);
if (restIndex != -1 && restIndex != i) {
result = [i, restIndex];
break;
}
}
return result;
};
the case restIndex === i
was not considered the first time I submitted so I add restIndex != i
in if
condition
we can also set the second parameter of indexOf
to avoid that case
so the restIndex
calucation can be changed to let restIndex = nums.indexOf(rest, i + 1);
some other good methods
using ES6 data structure Map
var twoSum = function(nums, target) {
let map = new Map();
for (let i = 0; i < nums.length; i++) {
let rest = target - nums[i];
if (map.get(rest) != undefined) {
result = [i, map.get(rest)];
return result;
} else {
map.set(nums[i], i);
}
}
return [0, 0]
};
this is more efficient
we need to notice the case
map.get(rest) === 0
and we can instead map to an ordinary object
var twoSum = function(nums, target) {
let obj = {};
for (let i = 0; i < nums.length; i++) {
let rest = target - nums[i];
if (obj[rest] != undefined) {
result = [obj[rest], i];
return result;
} else {
obj[nums[i]] = i;
}
}
return [0, 0]
};
网友评论