Skip to content

Instantly share code, notes, and snippets.

@vigack
Last active May 11, 2018 07:50
Show Gist options
  • Save vigack/3005460a0f42015c7d2e93ad760ceb88 to your computer and use it in GitHub Desktop.
Save vigack/3005460a0f42015c7d2e93ad760ceb88 to your computer and use it in GitHub Desktop.
3sum
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort
solutions = []
d = {}
inx = 0
# build index
for num in nums:
d[num] = d.get(num, []).append(inx)
inx += 1
# loop
for i in len(nums):
if nums[i] > 0:
return solutions
for j in range(i+1, len(nums)):
sp = 0 - nums[i] - nums[j]
if sp in d:
for s in d[sp]:
if s > j:
solutions.append([nums[i],nums[j],nums[s]])
return solutions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment