Skip to content

Commit fd093e9

Browse files
committed
Two Sum
1 parent bb0db1a commit fd093e9

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

two-sum/sunjae95.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* 1. O(n^2) brute force
5+
* 2. hash table
6+
*/
7+
8+
/**
9+
* @description brainstorming 1 solve
10+
* time complexity: O(n^2)
11+
* space complexity: O(n)
12+
*/
13+
var twoSum = function (nums, target) {
14+
for (let i = 0; i < nums.length; i++) {
15+
for (let j = i + 1; j < nums.length; j++) {
16+
if (nums[i] + nums[j] === target) return [i, j];
17+
}
18+
}
19+
};
20+
21+
/**
22+
* @description brainstorming 2 solve
23+
* time complexity: O(n^2)
24+
* space complexity: O(n)
25+
*/
26+
var twoSum = function (nums, target) {
27+
const map = new Map();
28+
29+
nums.forEach((num, index) => {
30+
if (!map.get(num)) return map.set(num, [index]);
31+
32+
map.set(num, map.get(num).concat(index));
33+
});
34+
35+
for (let i = 0; i < nums.length; i++) {
36+
const rest = target - nums[i];
37+
38+
if (!map.get(rest)) continue;
39+
40+
const indexList = map.get(rest);
41+
for (let j = 0; j < indexList.length; j++) {
42+
if (i === indexList[j]) continue;
43+
44+
return [i, indexList[j]];
45+
}
46+
}
47+
};

0 commit comments

Comments
 (0)