-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3sum.py
26 lines (24 loc) · 787 Bytes
/
3sum.py
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
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
if n < 3:
return []
triplets = set()
nums.sort()
for i in range(n - 2):
a = nums[i]
start = i + 1
end = n - 1
while start < end:
b = nums[start]
c = nums[end]
total = a + b + c
if total == 0:
triplets.add(tuple(sorted([a, b, c])))
start += 1
end -= 1
elif total > 0:
end -= 1
else:
start += 1
return [list(triplet) for triplet in triplets]