forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcount85.py
More file actions
54 lines (40 loc) ยท 1.73 KB
/
gcount85.py
File metadata and controls
54 lines (40 loc) ยท 1.73 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
"""
# Intuition
์ฒ์์๋ 1์ฃผ์ฐจ์ Two Sum ๋ฌธ์ ํ์ด๋ฅผ ์์ฉํ์ฌ, ๋ฐฐ์ด ์ํ + ํด์ ํ
์ด๋ธ ๋ง๋ค์ด ๊ฐ ์ฐพ๊ธฐ๋ฅผ ์๋ํ์ผ๋
์ ๋ ฌ + ํฌํฌ์ธํฐ ํ์ด๊ฐ ๋ ๋น ๋ฅด๋ฏ๋ก ๊ทธ๋ ๊ฒ ์ ์ถํ์ต๋๋ค.
# Approach
nums ๋ฐฐ์ด์ ์ํํ๋ฉด์ -nums[i]๋ฅผ ํฉ์ผ๋ก ํ๋ ๋ ์๋ฅผ ๋๋จธ์ง ๋ฐฐ์ด ๋ถ๋ถ์์ ์ฐพ๋๋ค.
์ฐพ์ ๋๋ ์ ๋ ฌ & ํฌํฌ์ธํฐ๋ฅผ ํ์ฉํ์ฌ ์ค๋ณต์ ๊ฑด๋ ๋ฐ๋ ๋ฐฉ์์ผ๋ก ์๋๋ฅผ ๋์ธ๋ค.
# Complexity
- Time complexity: ์ ๋ ฌ + ํฌํฌ์ธํฐ ์ด์ค ๋ฐ๋ณต์ผ๋ก O(N^2)
- Space complexity: ์ ๋ ฌ ํ๋๋ฐ์ O(N) , answer ๋ฐฐ์ด ์์ฑํ๋๋ฐ์ O(M)
"""
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
nums.sort() # O(NlogN)
n = len(nums)
answer = []
for i in range(n - 2): # ์ด์ค ๋ฐ๋ณต๋ฌธ O(N^2)
# ์ค๋ณต ์ ๊ฑฐ
if i > 0 and nums[i] == nums[i - 1]:
continue
# nums[i]๊ฐ 0๋ณด๋ค ํฌ๋ฉด ๋ค๋ ๋ค ์์๋ผ ์ข
๋ฃ ๊ฐ๋ฅ
if nums[i] > 0:
break
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
answer.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
# left/right ์ค๋ณต ์ ๊ฑฐ
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return answer