Skip to content

Instantly share code, notes, and snippets.

@munguial
Created July 15, 2020 05:45
Show Gist options
  • Save munguial/c52172d9b58068fa7eeeb1c1d9f37106 to your computer and use it in GitHub Desktop.
Save munguial/c52172d9b58068fa7eeeb1c1d9f37106 to your computer and use it in GitHub Desktop.
July - Day 8 - Three Sum
# https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3384/
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = set()
nums.sort()
for i in range(len(nums)):
if nums[i] > 0:
continue
self.twoSum(nums, -nums[i], i, res)
return list(res)
def twoSum(self, nums: List[int], target: int, i: int, res: List[int]):
start = i + 1
end = len(nums) - 1
while start < end:
if nums[start] + nums[end] == target:
res.add(tuple(sorted([nums[start], nums[end], -target])))
start += 1
end -= 1
elif nums[start] + nums[end] < target:
start += 1
else:
end -= 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment