15. 3Sum
Medium
Problem:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter.Solutions:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
left, right = 0, len(nums) - 1
while left < len(nums) - 2:
ptr = left + 1
while ptr < right:
if nums[left] + nums[ptr] + nums[right] == 0:
tmp = sorted([nums[left], nums[ptr], nums[right]])
# check duplicates
if tmp not in res:
res.append(tmp)
ptr += 1
while ptr < right and nums[ptr] == nums[ptr - 1]:
ptr += 1
elif nums[left] + nums[ptr] + nums[right] < 0:
ptr += 1
else:
right -= 1
left += 1
# Reset the right pointer
right = len(nums) - 1
return resTwo Pointers
Last updated