Skip to content

Commit

Permalink
feature: three sum revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Dec 6, 2023
1 parent 1d4d9b9 commit da8b7c2
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions arrays/ThreeSum.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,16 @@
# O(n^2) time || O(1) space
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = []
res = []
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue

low, high = i + 1, len(nums) - 1
while low < high:
sum_ = nums[i] + nums[low] + nums[high]

if sum_ == 0:
triplets.append([nums[i], nums[low], nums[high]])
_sum = nums[i] + nums[low] + nums[high]
if _sum == 0:
res.append([nums[i], nums[low], nums[high]])
low, high = low + 1, high - 1

while low < high and nums[low] == nums[low - 1]:
Expand All @@ -23,9 +22,9 @@ def three_sum(self, nums: List[int]) -> List[List[int]]:
while low < high and nums[high] == nums[high + 1]:
high -= 1

elif sum_ < 0:
elif _sum < 0:
low += 1
else:
high -= 1

return triplets
return res

0 comments on commit da8b7c2

Please sign in to comment.