Skip to content

Commit 5281a74

Browse files
committed
3sum solutions
1 parent 9cd97d9 commit 5281a74

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

3sum/hyeri0903.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from itertools import combinations
2+
3+
class Solution:
4+
def threeSum(self, nums: List[int]) -> List[List[int]]:
5+
"""
6+
time complexity : O(n^2)
7+
space complexity : O(1)
8+
"""
9+
answer = []
10+
nums.sort()
11+
n = len(nums)
12+
13+
for i in range(n):
14+
#skipped if nums[i] == nums[i-1] to avoid duplicate triplets
15+
if i > 0 and nums[i] == nums[i-1]:
16+
continue
17+
18+
#search with two pointer
19+
left, right = i+1, n-1
20+
21+
while left < right:
22+
total = nums[left] + nums[i] + nums[right]
23+
if total == 0:
24+
answer.append([nums[left], nums[i], nums[right]])
25+
26+
#move the pointers past duplicates
27+
while left < right and nums[left] == nums[left+1]:
28+
left += 1
29+
while left < right and nums[right] == nums[right-1]:
30+
right -= 1
31+
32+
left += 1
33+
right -= 1
34+
elif total < 0:
35+
left += 1
36+
else:
37+
right -= 1
38+
39+
return answer

0 commit comments

Comments
 (0)