Advertisement
smj007

Untitled

Aug 2nd, 2023
1,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1.  
  2. # sort and then use two pointers. avoiding duplicates was the real hassle. difficult implementation
  3.  
  4. class Solution:
  5.     def threeSum(self, nums: List[int]) -> List[List[int]]:
  6.  
  7.         nums.sort()
  8.         result = []
  9.         nums = list(set(nums))
  10.  
  11.         for index, num in enumerate(nums):
  12.            
  13.             # not needed, it's optimisation over the current approach to save
  14.             # some computation time
  15.             if num > 0:
  16.                 break
  17.  
  18.             # avoid duplicates
  19.             if index!=0 and nums[index] == nums[index-1]:
  20.                 continue
  21.  
  22.             target = -num
  23.  
  24.             start = index + 1
  25.             end = len(nums) - 1
  26.  
  27.             while(start < end):
  28.  
  29.                 if nums[start] + nums[end] < target:
  30.                     start = start + 1
  31.                 elif nums[start] + nums[end] > target:
  32.                     end = end - 1
  33.                 else:
  34.                     result.append([nums[index], nums[start], nums[end]])
  35.                     start = start + 1
  36.                     end = end - 1
  37.  
  38.                     while(start < end and nums[start] == nums[start-1]):
  39.                         start = start + 1
  40.  
  41.                     while(start < end and nums[end] == nums[end+1]):
  42.                         end = end - 1
  43.  
  44.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement