Skip to content

Instantly share code, notes, and snippets.

@guyskk
Created May 29, 2018 02:33
Show Gist options
  • Save guyskk/f764d48671b26ab9dce27c3acdb15cc2 to your computer and use it in GitHub Desktop.
Save guyskk/f764d48671b26ab9dce27c3acdb15cc2 to your computer and use it in GitHub Desktop.
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums = sorted(nums)
res = []
n = len(nums)
for i in range(n-2):
if i==0 or (i>0 and nums[i]!=nums[i-1]):
l, r = i+1, n-1
while l < r:
sum = nums[i]+nums[r]+nums[l]
if sum == 0:
new = [nums[i], nums[r], nums[l]]
res.append(new)
while l<r and nums[l] == nums[l+1]:
l+=1
while l<r and nums[r] == nums[r-1]:
r-=1
elif sum > 0:
r -= 1
elif sum < 0:
l += 1
l += 1
r -= 1
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment