Skip to content

Instantly share code, notes, and snippets.

@ericness
Last active February 5, 2022 23:40
Show Gist options
  • Select an option

  • Save ericness/e0b87774325b273d607b62db81b9fbf4 to your computer and use it in GitHub Desktop.

Select an option

Save ericness/e0b87774325b273d607b62db81b9fbf4 to your computer and use it in GitHub Desktop.
LeetCode 15 passing solution
import copy
from collections import defaultdict
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
"""Find unique triplets that sum to zero.
Args:
nums (List[int]): List of numbers
Returns:
List[List[int]]: List of triplets that sum to zero
"""
result = []
for i in range(len(nums)):
nums_set = set()
for j in range(i + 1, len(nums)):
if -(nums[i] + nums[j]) in nums_set:
new_result = sorted(
[
nums[i],
nums[j],
-(nums[i] + nums[j]),
]
)
if new_result not in result:
result.append(new_result)
else:
nums_set.add(nums[j])
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment