Skip to content

Commit 6642c7b

Browse files
committed
feat: [Week 02-3] solve 3 sum
1 parent f00520e commit 6642c7b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

3sum/Chaedie.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
첫번째 풀이 -> 달레의 코드 풀이
3+
1) sort와 two pointer를 활용한 풀이
4+
2) has_set 을 활용한 중복 제거
5+
6+
두번째 풀이 -> Neetcode 풀이
7+
1) sort와 two pointer를 활용한 풀이
8+
2) while loop 를 활용한 중복 제거
9+
10+
Time: O(n) = O(n) + O(n)
11+
Space: O(n)
12+
"""
13+
14+
15+
class Solution:
16+
def threeSum(self, nums: List[int]) -> List[List[int]]:
17+
nums.sort()
18+
res = set()
19+
n = len(nums)
20+
21+
for i in range(n):
22+
l, r = i + 1, n - 1
23+
while l < r:
24+
summ = nums[i] + nums[l] + nums[r]
25+
if summ < 0:
26+
l += 1
27+
elif summ > 0:
28+
r -= 1
29+
else:
30+
res.add((nums[i], nums[l], nums[r]))
31+
l += 1
32+
return list(res)
33+
34+
35+
class Solution:
36+
def threeSum(self, nums: List[int]) -> List[List[int]]:
37+
nums.sort()
38+
res = []
39+
n = len(nums)
40+
41+
for i in range(n):
42+
l, r = i + 1, n - 1
43+
44+
if i > 0 and nums[i] == nums[i - 1]:
45+
continue
46+
47+
while l < r:
48+
summ = nums[i] + nums[l] + nums[r]
49+
if summ < 0:
50+
l += 1
51+
elif summ > 0:
52+
r -= 1
53+
else:
54+
res.append([nums[i], nums[l], nums[r]])
55+
l += 1
56+
while nums[l] == nums[l - 1] and l < r:
57+
l += 1
58+
59+
return res

0 commit comments

Comments
 (0)