Skip to content

Commit c64c254

Browse files
committed
feat: solve two-sum
1 parent a7426ad commit c64c254

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

two-sum/sujeong-dev.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
7+
// 2중 for문: O(n^2)
8+
var twoSum = function (nums, target) {
9+
for (let i = 0; i < nums.length; i++) {
10+
for (let j = 0; j < nums.length; j++) {
11+
if (i === j) continue;
12+
if (nums[i] + nums[j] === target) return [i, j];
13+
}
14+
}
15+
};
16+
17+
// for loof: O(n)
18+
var twoSum = function (nums, target) {
19+
let result = {};
20+
21+
nums.forEach((num, index) => {
22+
result[num] = index;
23+
});
24+
25+
for (let i = 0; i < nums.length; i++) {
26+
const findNum = target - nums[i];
27+
28+
if (findNum in result && result[findNum] !== i) {
29+
return [i, result[findNum]];
30+
}
31+
}
32+
};

0 commit comments

Comments
 (0)