Skip to content

Commit ffc71a6

Browse files
committed
solve two-sum
1 parent 19d7689 commit ffc71a6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

two-sum/1lsang.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// 1. 가장 간단한 방법 이중 for문 (Runtime: 175ms / Memory: 55.8MB)
2+
// function twoSum(nums: number[], target: number): number[] {
3+
// const length = nums.length;
4+
// for (let i = 0; i < length; i++) {
5+
// for (let j = 0; j < length; j++) {
6+
// if (i === j) continue;
7+
// if (nums[i] + nums[j] === target) return [i, j]
8+
// }
9+
// }
10+
// return [];
11+
// };
12+
13+
// 2. 시간 복잡도 개선 (Runtime: 9ms / Memory: 60.4MB)
14+
function twoSum(nums: number[], target: number): number[] {
15+
const numObj = {};
16+
nums.forEach((num, index) => {numObj[num] ? numObj[num].push(index) : numObj[num]=[index]});
17+
for (let i = 0; i<nums.length; i++) {
18+
const num = target - nums[i];
19+
if (numObj[num]?.length === 1) {
20+
if (i === numObj[num][0]) continue;
21+
return [i, numObj[num][0]];
22+
}
23+
else if (numObj[num]?.length === 2) {
24+
return numObj[num];
25+
}
26+
}
27+
return [];
28+
};

0 commit comments

Comments
 (0)