forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYjason-K.ts
53 lines (49 loc) ยท 1.84 KB
/
Yjason-K.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* ์ธ ์์ ํฉ์ด 0์ด ๋๋ ๋ชจ๋ ๊ณ ์ ํ ์กฐํฉ์ ์ฐพ๋ ํจ์
*
* @param {number[]} nums - ์ ์ ๋ฐฐ์ด
* @returns {number[][]} - ์ธ ์์ ํฉ์ด 0์ด ๋๋ ์กฐํฉ ๋ฐฐ์ด
*
* 1. ์
๋ ฅ ๋ฐฐ์ด `nums`๋ฅผ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ.
* 2. ์ด์ค ๋ฐ๋ณต๋ฌธ์ ์ฌ์ฉํ์ฌ ๊ฐ ์์๋ฅผ ๊ธฐ์ค์ผ๋ก `ํฌ ํฌ์ธํฐ(two-pointer)`๋ฅผ ์ด์ฉํด ์กฐํฉ์ ํ์.
* 3. ์ค๋ณต ์กฐํฉ์ ๋ฐฉ์งํ๊ธฐ ์ํด `Set`์ ์ฌ์ฉํ์ฌ ๊ฒฐ๊ณผ ์กฐํฉ์ ๋ฌธ์์ด์ ์ ์ฅ.
* 4. ์กฐ๊ฑด์ ๋ง๋ ์กฐํฉ์ `result` ๋ฐฐ์ด์ ์ถ๊ฐํฉ๋๋ค.
*
* ์๊ฐ ๋ณต์ก๋:
* - ์ ๋ ฌ: O(n log n)
* - ์ด์ค ๋ฐ๋ณต๋ฌธ ๋ฐ ํฌ ํฌ์ธํฐ: O(n^2)
* - ์ ์ฒด ์๊ฐ ๋ณต์ก๋: O(n^2)
*
* ๊ณต๊ฐ ๋ณต์ก๋:
* - `Set` ๋ฐ `result` ๋ฐฐ์ด์ ์ ์ฅ๋๋ ๊ณ ์ ์กฐํฉ: O(k), k๋ ๊ณ ์ ํ ์กฐํฉ์ ์
* - ์ ์ฒด ๊ณต๊ฐ ๋ณต์ก๋: O(n + k)
*/
function threeSum(nums: number[]): number[][] {
const sumSet = new Set<string>();
const result: number[][] = [];
nums.sort((a, b) => a - b);
// ์ฒซ ๋ฒ์งธ ์์๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฐ๋ณต๋ฌธ ์ํ
for (let i = 0; i < nums.length - 2; i++) {
// ์ ๋ ฌ ๋ ์ํ์ด๊ธฐ ๋๋ฌธ์ ์์์ ์ ๊ธฐ์ค์ผ๋ก ๋ค์ ๊ฐ ์ค๋ณต ๋น๊ต
if (i > 0 && nums[i] === nums[i - 1]) continue;
let start = i + 1, end = nums.length - 1;
while (start < end) {
const sum = nums[i] + nums[start] + nums[end];
if (sum > 0) {
end--;
} else if (sum < 0) {
start++;
} else {
const triplet = [nums[i], nums[start], nums[end]];
const key = triplet.toString();
if (!sumSet.has(key)) {
sumSet.add(key);
result.push(triplet);
}
start++;
end--;
}
}
}
return result;
}