forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSeoya0512.py
More file actions
78 lines (61 loc) ยท 3.05 KB
/
Seoya0512.py
File metadata and controls
78 lines (61 loc) ยท 3.05 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from typing import List
'''
1์ฐจ ์๋: ์คํจ (์๊ฐ ์ด๊ณผ)
- nums์์ ๋ ์ (A,B)๋ฅผ ๊ณ ๋ฅธ ํ, ์ธ๋ฒ์งธ ์ซ์์ธ -(A+B)๊ฐ A,B๋ฅผ ์ ์ธํ nums์ ์กด์ฌํ๋์ง ํ์ธ
- ์ค๋ณต๋ ๊ฒฐ๊ณผ๋ฅผ ์ ๊ฑฐํ๊ธฐ ์ํด set๊ณผ sorted(tuple)์ ํ์ฉ
์๊ฐ ๋ณต์ก๋: O(N^3)
- Outer loop์ Inner loop ๊ฐ๊ฐ O(N) ์ด๋ฏ๋ก O(N^2)์ ๊ธฐ๋ณธ
- nums[j:]์์ third_num์ ์ฐพ๋ ๋ฐ O(N) ์๊ฐ์ด ๊ฑธ๋ ค์ ์ ์ฒด ์๊ฐ ๋ณต์ก๋๋ O(N^3)
๊ณต๊ฐ ๋ณต์ก๋: ์ต๋ O(N^2)
- answer_set์ ์ค๋ณต๋์ง ์๋ triplet์ ์ ์ฅํ๋ฉฐ, 3SUM ํน์ฑ์ ์ ๋ํฌํ triplet์ ์ต๋ ๊ฐ์๋ O(N^2)
'''
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
answer_set = set()
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
third_num = -1 * (nums[i] + nums[j])
if third_num in nums[j:]:
answer_set.add(tuple(sorted([nums[i], nums[j], third_num])))
return [list(t) for t in answer_set]
'''
๊ฐ์ : if third_num in nums[j:] ๋ถ๋ถ์ set์ ํ์ฉ
Approach
- nums์์ ๋ ์ (A,B)๋ฅผ ๊ณ ๋ฅธ ํ, ์ธ๋ฒ์งธ ์ซ์์ธ -(A+B)๊ฐ ์กด์ฌํ๋์ง ํ์ธํ๋ ๊ธฐ์กด ๊ธฐ์กฐ๋ ์ ์งํจ
- (A,B) ์ ์ค โA(์ฒซ ๋ฒ์งธ ์ซ์)โ๊ฐ ๋์ผํ ๊ฐ์ผ ๋,
์ด๋ฏธ ๋์ผํ first ๊ฐ์ผ๋ก ์์ฑํ ์ ์๋ ๋ชจ๋ triplet์ ์ฒ๋ฆฌํ์ผ๋ฏ๋ก
๋ค์ ๊ฐ์ first๋ก ์์ํ๋ ์กฐํฉ์ ๋ง๋ค ํ์๊ฐ ์๋ค๋ ์ ์ ํ์ฉ
- seen set์ ํ์ฉํด์ (A,B)๊ฐ ๊ณ ์ ๋ ์ดํ ์ธ๋ฒ์งธ ์ซ์์ธ -(A+B)๊ฐ ์กด์ฌํ๋์ง O(1) ์๊ฐ์ ํ์ธ
- (์์) seen set์ i๊ฐ ๊ณ ์ ๋ ์ดํ j๋ฅผ ์ํํ๋ฉด์ nums[j] ๊ฐ์ ์ ์ฅ
- nums = [a, b, c, d, e]
- i = 0 (nums[i] = a)์ผ ๋, seen = {}
- j = 1 (nums[j] = b)์ผ ๋, seen = {b}
- j = 2 (nums[j] = c)์ผ ๋, seen = {b, c}
- j = 3 (nums[j] = d)์ผ ๋, seen = {b, c, d}
- j = 4 (nums[j] = e)์ผ ๋, seen = {b, c, d, e)
์๊ฐ ๋ณต์ก๋: O(N^2)
- Outer loop์ Inner loop ๊ฐ๊ฐ O(N) ์ด๋ฏ๋ก ์ ์ฒด ์๊ฐ ๋ณต์ก๋๋ O(N^2)
๊ณต๊ฐ ๋ณต์ก๋: ์ต๋ O(N^2)
- seen set์ nums[j]๋ฅผ ์ ์ฅํ๋ฉฐ ์ต์
์ ๊ฒฝ์ฐ O(N)
- used_first๋ distinct first ๊ฐ๋ค์ ์ ์ฅํ๋ฉฐ ์ต๋ O(N)
- answer_set์ ์ค๋ณต๋์ง ์๋ triplet์ ์ ์ฅํ๋ฉฐ, 3SUM ํน์ฑ์ ์ ๋ํฌํ triplet์ ์ต๋ ๊ฐ์๋ O(N^2)
'''
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
answer_set = set()
n = len(nums)
used_first = set() # ์ด๋ฏธ i๋ก ์ฌ์ฉํ ๊ฐ๋ค
for i in range(n - 1):
# ๊ฐ์ ๊ฐ์ ์ฒซ ๋ฒ์งธ ์ซ์๋ก ํ ๋ฒ๋ง ์ฐ๊ธฐ
if nums[i] in used_first:
continue
used_first.add(nums[i])
seen = set()
for j in range(i + 1, n):
third_num = -1 * (nums[i] + nums[j])
if third_num in seen:
triplet = tuple(sorted([nums[i], nums[j], third_num]))
answer_set.add(triplet)
else:
seen.add(nums[j])
return [list(t) for t in answer_set]