Skip to content

Commit 741936b

Browse files
committed
3sum solution
1 parent ac12f16 commit 741936b

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

3sum/Blossssom.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @param nums - 정수 배열
3+
* @returns - 세 요소를 합해 0이 되는 값의 배열
4+
* @description
5+
* - 투 포인터 방식
6+
* - 결국 유니크한 조합을 찾으며 중복을 제외하는 방향
7+
* - 무조건 적인 반복 줄이기가 아닌 효율적 범위 반복을 학습해야함
8+
* - 시간 복잡도 O(N^2)
9+
* - 공간 복잡도 O(log N)
10+
*/
11+
function threeSum(nums: number[]): number[][] {
12+
const answer: number[][] = [];
13+
nums.sort((a, b) => a - b);
14+
15+
for (let i = 0; i < nums.length - 2; i++) {
16+
if (i && nums[i] === nums[i - 1]) {
17+
continue;
18+
}
19+
20+
let left = i + 1;
21+
let right = nums.length - 1;
22+
23+
while (left < right) {
24+
const sum = nums[i] + nums[left] + nums[right];
25+
26+
if (sum === 0) {
27+
answer.push([nums[i], nums[left], nums[right]]);
28+
while (left < right && nums[left] === nums[left + 1]) {
29+
left++;
30+
}
31+
while (left < right && nums[right] === nums[right - 1]) {
32+
right--;
33+
}
34+
left++;
35+
right--;
36+
} else if (sum < 0) {
37+
left++;
38+
} else {
39+
right--;
40+
}
41+
}
42+
}
43+
44+
return answer;
45+
}
46+
47+
const nums = [-1, 0, 1, 2, -1, -4];
48+
threeSum(nums);
49+

product-of-array-except-self/Blossssom.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,4 @@ function productExceptSelf(nums: number[]): number[] {
3232

3333
const nums = [1, 2, 3, 4];
3434
productExceptSelf(nums);
35+

0 commit comments

Comments
 (0)