Skip to content

Commit d29a266

Browse files
committed
Solve: 3sum
1 parent 3a3e87b commit d29a266

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

3sum/hj4645.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
nums.sort() # 배열 정렬해서 중복 처리와 투 포인터에 유리하게 만듦
4+
n = len(nums)
5+
answer = []
6+
7+
for i in range(n - 2):
8+
# i가 0이 아니면서 이전 값과 같으면 중복 방지를 위해 건너뜀
9+
if i > 0 and nums[i] == nums[i - 1]:
10+
continue
11+
12+
left, right = i + 1, n - 1
13+
14+
while left < right:
15+
total = nums[i] + nums[left] + nums[right]
16+
17+
if total == 0:
18+
answer.append([nums[i], nums[left], nums[right]])
19+
20+
# left와 right가 가리키는 값이 중복이면 넘어감
21+
while left < right and nums[left] == nums[left + 1]:
22+
left += 1
23+
while left < right and nums[right] == nums[right - 1]:
24+
right -= 1
25+
26+
left += 1
27+
right -= 1
28+
elif total < 0:
29+
left += 1
30+
else:
31+
right -= 1
32+
33+
return answer
34+
35+

0 commit comments

Comments
 (0)