Skip to content

Instantly share code, notes, and snippets.

@sushinoya
Created June 26, 2019 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sushinoya/e9cd40dd05f3ecc2e90105cc316fb881 to your computer and use it in GitHub Desktop.
Save sushinoya/e9cd40dd05f3ecc2e90105cc316fb881 to your computer and use it in GitHub Desktop.
3Sum using a dictionary
class Solution:
def threeSum(self, nums):
if all(map(lambda x: x == 0, nums)):
if len(nums) >= 3:
return [[0,0,0]]
else:
return []
positives = [x for x in nums if x > 0]
negatives = [x for x in nums if x <= 0]
positives_set = set(positives)
negatives_set = set(negatives)
ret = set()
if nums.count(0) >= 3:
ret.add((0,0,0))
for i in range(len(positives)):
for j in range(len(positives)):
if i == j:
continue
if 0 - (positives[i] + positives[j]) in negatives_set:
ret.add(tuple(sorted((0 - (positives[i] + positives[j]), positives[i], positives[j]))))
for i in range(len(negatives)):
for j in range(len(negatives)):
if i == j:
continue
if 0 - (negatives[i] + negatives[j]) in positives_set:
ret.add(tuple(sorted((0 - (negatives[i] + negatives[j]), negatives[i], negatives[j]))))
return [ list(x) for x in ret ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment