X Algorithm
Search…
Two Sum
1
var twoSum = function(nums, target) {
2
3
// brute force
4
for (let i =0; i< nums.length; i++ ) {
5
6
let i1 = i;
7
let tmpTarget = target - nums[i];
8
9
for (let j = i+1; j< nums.length; j++) {
10
if (nums[j] === tmpTarget) {
11
return [i,j];
12
}
13
}
14
}
15
};
Copied!
​
Use HashMap
1
function twoSum(nums, target) {
2
vToIndex = {};
3
4
for (let i =0; i< nums.length; i++) {
5
let tmpTarget = target - nums[i];
6
7
if (tmpTarget in vToIndex) {
8
return [i, vToIndex[tmpTarget]];
9
} else {
10
vToIndex[nums[i]] = i;
11
}
12
}
13
}
Copied!
Last modified 1mo ago
Copy link