Created
June 26, 2019 02:13
-
-
Save sushinoya/e9cd40dd05f3ecc2e90105cc316fb881 to your computer and use it in GitHub Desktop.
3Sum using a dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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