Skip to content

Commit eddea6e

Browse files
committed
feat: 3sum solution
1 parent 7dc8c64 commit eddea6e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

3sum/YeomChaeeun.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 세 숫자의 합이 0이 되는 조합 찾기
3+
* 알고리즘 복잡도:
4+
* - 시간복잡도: O(n^2)
5+
* - 공간복잡도: O(1)
6+
* @param nums
7+
*/
8+
function threeSum(nums: number[]): number[][] {
9+
// 정렬
10+
nums.sort((a, b) => a - b)
11+
let result: number[][] = []
12+
13+
// 투포인터
14+
for (let i = 0; i < nums.length - 2; i++) {
15+
if (i > 0 && nums[i] === nums[i - 1]) continue;
16+
17+
let start = i + 1
18+
let end = nums.length - 1
19+
const target = -nums[i] // 고정 숫자를 이용
20+
// start + end + target === 0 이므로, start + end === -target
21+
22+
while (start < end) {
23+
const sum = nums[start] + nums[end]
24+
if (sum === target) {
25+
result.push([nums[i], nums[start], nums[end]])
26+
27+
// 배열 중복 값 건너뛰기
28+
while (start < end && nums[start] === nums[start + 1]) start++
29+
while (start < end && nums[start] === nums[end - 1]) end--
30+
31+
// 포인터 이동
32+
start++
33+
end--
34+
} else if (sum < target) {
35+
start++
36+
} else {
37+
end--
38+
}
39+
}
40+
}
41+
return result
42+
}

0 commit comments

Comments
 (0)