-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_3Sum.py
More file actions
30 lines (24 loc) · 909 Bytes
/
Copy path15_3Sum.py
File metadata and controls
30 lines (24 loc) · 909 Bytes
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
27
28
29
30
class Solution:
def threeSum(self, nums: list[int]) -> list[list[int]]:
nums.sort()
res = []
for p in range(len(nums)):
if p != 0 and nums[p] == nums[p - 1]:
continue
left = p + 1
right = len(nums) - 1
target = -nums[p]
while(left < right):
if nums[left] + nums[right] < target:
left += 1
elif nums[left] + nums[right] > target:
right -= 1
else:
res.append([nums[left], nums[right], nums[p]])
left += 1
right -= 1
while(nums[left] == nums[left - 1] and left < right):
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return res