LyWang

3sum

Nov 25th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. class Solution:
  2.     """
  3.    @param numbers: Give an array numbers of n integer
  4.    @return: Find all unique triplets in the array which gives the sum of zero.
  5.    """
  6.     def threeSum(self, nums):
  7.         res = []
  8.         nums.sort()
  9.         for i in range(len(nums)-2):
  10.             if i > 0 and nums[i] == nums[i-1]:
  11.                 continue
  12.             l, r = i+1, len(nums)-1
  13.             while l < r:
  14.                 s = nums[i] + nums[l] + nums[r]
  15.                 if s < 0:
  16.                     l +=1
  17.                 elif s > 0:
  18.                     r -= 1
  19.                 else:
  20.                     res.append((nums[i], nums[l], nums[r]))
  21.                     while l < r and nums[l] == nums[l+1]:
  22.                         l += 1
  23.                     while l < r and nums[r] == nums[r-1]:
  24.                         r -= 1
  25.                     l += 1; r -= 1
  26.         return res
Add Comment
Please, Sign In to add comment