Skip to content

Commit 64ebc44

Browse files
committed
3 sum solution
1 parent 564f163 commit 64ebc44

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

3sum/devyejin.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution:
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
nums.sort() # O(n)
4+
5+
n = len(nums)
6+
result = []
7+
8+
for i in range(n - 2):
9+
# target을 잡을때도 이전에 구했다면 패스
10+
if i > 0 and nums[i] == nums[i - 1]:
11+
continue
12+
13+
target = - nums[i]
14+
left, right = i + 1, n - 1
15+
16+
while left < right:
17+
two_sum = nums[left] + nums[right]
18+
19+
if two_sum == target:
20+
result.append([nums[i], nums[left], nums[right]])
21+
22+
while left < right and nums[left] == nums[left + 1]:
23+
left += 1
24+
25+
while left < right and nums[right] == nums[right - 1]:
26+
right -= 1
27+
28+
left += 1
29+
right -= 1
30+
31+
elif two_sum < target:
32+
left += 1
33+
else:
34+
right -= 1
35+
36+
return result

0 commit comments

Comments
 (0)