https://leetcode.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
print(nums)
solutions = []
for i, v in enumerate(nums):
if i > 0 and nums[i] == nums[i -1]:
continue
if i > len(nums)-3:
break
beg = i + 1
end = len(nums) - 1
while end > beg:
sum3 = v + nums[beg] + nums[end]
if sum3 > 0:
end -= 1
elif sum3 < 0:
beg += 1
else:
solutions.append([v, nums[beg], nums[end]])
while (beg < end and nums[beg] == nums[beg +1]):
beg += 1
beg += 1
while (beg < end and nums[end] == nums[end -1]):
end -= 1
end -= 1
return solutions