nathanwailes

LeetCode 15 - 3Sum - NeetCode solution

Oct 9th, 2023
823
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. class Solution:
  2.     def threeSum(self, nums: List[int]) -> List[List[int]]:
  3.         res = []
  4.         nums.sort()
  5.  
  6.         for i, a in enumerate(nums):
  7.             if i > 0 and a == nums[i - 1]:
  8.                 continue
  9.            
  10.             l, r = i + 1, len(nums) - 1
  11.             while l < r:
  12.                 threeSum = a + nums[l] + nums[r]
  13.                 if threeSum > 0:
  14.                     r -= 1
  15.                 elif threeSum < 0:
  16.                     l += 1
  17.                 else:
  18.                     res.append([a, nums[l], nums[r]])
  19.                     l += 1
  20.                     while nums[l] == nums[l - 1] and l < r:
  21.                         l += 1
  22.         return res
Advertisement
Add Comment
Please, Sign In to add comment