Advertisement
goodwish

57. 3Sum

Nov 15th, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. a + b = -c, 3Sum reduces to 2Sum problem.
  2. [c, a, b]
  3.  
  4. * Handling Duplicates in 2Sum
  5.  
  6. Say index s and e are forming a solution in a sorted array. Now givens nums[s], there is a unique nums[e] such that nums[s] + nums[e] == Target. Therefore, if nums[s+1] is the same as nums[s], then searching in range s+1 to e will give us a duplicate solution. Thus we must move s till nums[s + 1] != nums[s] to avoid getting duplicates.
  7.  
  8. while s < e and A[s] == A[s + 1]:  # s, 正在处理的.
  9.   s = s + 1
  10.  
  11. * Handling Duplicates in 3Sum.
  12.  
  13. Imagine we are at index i and we have invoked the 2Sum problem from index i+1 to end of the array. Now once the 2Sum terminates, we will have a list of all triplets which include nums[i]. To avoid duplicates, we must skip all nums[i] where nums[i] == nums[i - 1].
  14.  
  15. if i > 0 and nums[i] == nums[i - 1]: # i - 1, 已经处理的.
  16.   continue
  17.  
  18. 外循环, 去重.
  19. a + b = -c, c = nums[i] 的两两组合已经全部求过, 所以跳过后边和 nums[i] 相等的数.
  20.  
  21. class Solution:
  22.     def threeSum(self, A):
  23.         # init
  24.         A.sort()
  25.         n = len(A)
  26.         res = []
  27.         # -5, -5, -5, 2, 3, 10
  28.         i = 0
  29.         while i < n - 2 and A[i] <= 0:
  30.             while i > 0 and i < n - 2 and A[i] == A[i - 1]:
  31.                 i += 1
  32.             c = A[i]
  33.             l, r = i + 1, n - 1
  34.             while l < r:
  35.                 if A[r] + A[l] > -c:
  36.                     r -= 1
  37.                 elif A[r] + A[l] < -c:
  38.                     l += 1
  39.                 else:
  40.                     res.append((c, A[l], A[r]))
  41.                     while l < r and A[l] == A[l + 1]:
  42.                         l += 1
  43.                     l += 1
  44.                     r -= 1
  45.             i += 1
  46.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement