forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZetBe.py
More file actions
43 lines (35 loc) ยท 1.71 KB
/
ZetBe.py
File metadata and controls
43 lines (35 loc) ยท 1.71 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
'''
๋ฌธ์ : ์ค๋ณต๋์ง ์๋ ์ธ ์์ ์กฐํฉ์ผ๋ก ํฉ์ด 0์ด ๋๋ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ์ฐพ๊ธฐ
ํ์ด: ์ ๋ ฌ๋ ๋ฐฐ์ด์์ ์ฒซ ๋ฒ์งธ ์๋ฅผ ๊ณ ์ ํ๊ณ , ๋๋จธ์ง ๋ ์๋ฅผ ํฌ ํฌ์ธํฐ๋ก ํ์
์๊ฐ๋ณต์ก๋: O(n^2)
๋ฐฐ์ด์ ์ ๋ ฌํ๋๋ฐ O(n log n), O(n)์ผ๋ก ์ํํ๋ฉฐ ๊ฐ ์์ ๋ํด ํฌ ํฌ์ธํฐ๋ก ๋๋จธ์ง ๋ ์๋ฅผ ์ฐพ๋๋ฐ O(n)์ด๋ฏ๋ก ์ ์ฒด ์๊ฐ๋ณต์ก๋๋ O(n^2)์ด๋ค.
๊ณต๊ฐ๋ณต์ก๋: O(1)
์ถ๊ฐ์ ์ธ ๊ณต๊ฐ์ ์ฌ์ฉํ์ง ์์ผ๋ฏ๋ก ์ ์ฒด ๊ณต๊ฐ๋ณต์ก๋๋ O(1)์ด๋ค.
์ฌ์ฉํ ์๋ฃ๊ตฌ์กฐ: ๋ฆฌ์คํธ
๋ณ๋์ ํ๊ณ : ์ ๋ต์ ์ค๋ณต๋ ์กฐํฉ์ด ๋ค์ด๊ฐ์ง ์๋๋ก ํ๊ธฐ ์ํด,
์ฒซ ๋ฒ์งธ ์๋ฅผ ๊ณ ์ ํ ๋ ์ด์ ์์ ๊ฐ์ ๊ฒฝ์ฐ๋ฅผ ๊ฑด๋๋ฐ๊ณ , ๋๋จธ์ง ๋ ์๋ฅผ ์ฐพ์ ๋๋ ์ธ ์์ ํฉ์ด 0์ผ ๊ฒฝ์ฐ, ๊ฐ ๋ ๋์ผํ ์๊ฐ ์ฐ์์ผ๋ก ๋์ค๋ ๊ฒฝ์ฐ๋ฅผ ๊ฑด๋๋ฐ๋๋ก ํ์๋ค.
'''
import ast
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
answer = []
for i in range(len(nums)-2):
if i > 0 and nums[i-1] == nums[i]:
continue
l, r = i+1, len(nums)-1
while l < r:
if nums[i] + nums[l] + nums[r] == 0:
arr = [nums[i], nums[l], nums[r]]
answer.append(arr[:])
while l < r and nums[l] == nums[l + 1]:
l+=1
while l < r and nums[r] == nums[r - 1]:
r-=1
l += 1
r -= 1
elif nums[i] + nums[l] + nums[r] < 0:
l += 1
else:
r -= 1
return answer