Skip to content

Commit 0366d40

Browse files
committed
Add two-sum solution
1 parent a69b246 commit 0366d40

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

two-sum/Jeehay28.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
8+
// Time Complexity : O(n)
9+
// Space Complexity : O(n)
10+
11+
var twoSum = function (nums, target) {
12+
13+
let map = new Map();
14+
15+
for (let i = 0; i < nums.length; i++) {
16+
17+
const temp = target - nums[i];
18+
19+
if (map.has(temp)) {
20+
return [i, map.get(temp)]
21+
}
22+
23+
map.set(nums[i], i);
24+
}
25+
26+
return [];
27+
}
28+
29+
30+
// Time Complexity: O(n^2)
31+
// Space Complexity: O(1)
32+
// This solution is straightforward but inefficient for large arrays. For better performance, consider the hashmap approach.
33+
34+
// var twoSum = function (nums, target) {
35+
36+
// for (let i = 0; i < nums.length; i++) {
37+
38+
// const loc = nums.indexOf((target - nums[i]), i + 1);
39+
40+
// if (loc >= 0) {
41+
// return [i, loc]
42+
// } else {
43+
// continue;
44+
// }
45+
46+
// }
47+
48+
// };
49+

0 commit comments

Comments
 (0)