Advertisement
jinhuang1102

15. 3Sum

Oct 19th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. class Solution:
  2.     def threeSum(self, nums):
  3.         """
  4.        :type nums: List[int]
  5.        :rtype: List[List[int]]
  6.        """
  7.         res = []
  8.         nums.sort()
  9.         for i in range(0, len(nums)-2):
  10.             # skip the duplicate
  11.             if i > 0 and nums[i-1] == nums[i]:
  12.                 continue
  13.            
  14.             # Get the target value
  15.             temp = 0 - nums[i]
  16.            
  17.             # Two pointer from start and end
  18.             l = i + 1
  19.             r = len(nums)-1
  20.            
  21.             while l < r:
  22.                 #在这个while Loop里面要用 if ... elif ... else ...
  23.                 if nums[l] + nums[r] == temp:
  24.                     # Get the target numbers group
  25.                     res.append([nums[i],nums[l],nums[r]])
  26.                    
  27.                     # skip the duplicate
  28.                     while l < r and nums[l] == nums[l+1]:
  29.                         l = l + 1
  30.                     while l < r and nums[r] == nums[r-1]:
  31.                         r = r - 1
  32.                     # Next pair numbers
  33.                     l = l + 1
  34.                     r = r - 1
  35.                    
  36.                 elif nums[l] + nums[r] < temp:
  37.                     l = l + 1
  38.                 else:
  39.                     r = r - 1
  40.            
  41.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement