smj007

Untitled

Jun 18th, 2022
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. class Solution:
  2.     def threeSum(self, nums: List[int]) -> List[List[int]]:
  3.        
  4.         nums.sort()
  5.         triplets = []
  6.        
  7.         for i in range(len(nums)):
  8.            
  9.             # avoid duplicates to begin with
  10.             if (i>0) and nums[i] == nums[i-1]:
  11.                 continue
  12.                
  13.             left = i + 1
  14.             right = len(nums) - 1
  15.            
  16.             while (left < right):
  17.  
  18.                 threeSum = nums[left] + nums[right] + nums[i]
  19.                
  20.                 # duplicates will automatically be taken care of
  21.                 # in the next 2 conditions; You don't have to separately do that
  22.                 # Also, you have
  23.                 if (threeSum > 0):
  24.                     right -= 1
  25.                 elif (threeSum < 0):
  26.                     left += 1
  27.                 else:
  28.                     triplets.append([nums[i], nums[left], nums[right]])
  29.                     left += 1
  30.                     right -= 1
  31.                    
  32.                     # avoid duplicates by running the while loop checks
  33.                     while(left < right and nums[left] == nums[left - 1]):
  34.                         left += 1
  35.                     while(left < right and nums[right] == nums[right + 1]):
  36.                         right -= 1
  37.                        
  38.         return triplets
Advertisement
Add Comment
Please, Sign In to add comment