Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2372 from ksfkwan/patch-1
Browse files Browse the repository at this point in the history
Update 0015-3sum.py
  • Loading branch information
MHamiid authored Mar 28, 2023
2 parents f16617a + fb06d5f commit 86ba5cd
Showing 1 changed file with 23 additions and 23 deletions.
46 changes: 23 additions & 23 deletions python/0015-3sum.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()

for i, a in enumerate(nums):
# Skip positive integers
if a > 0:
def ThreeSum(self, integers):
"""
:type integers: List[int]
:rtype: List[List[int]]
"""
integers.sort()
result = []
for index in range(len(integers)):
if integers[index] > 0:
break

if i > 0 and a == nums[i - 1]:
if index > 0 and integers[index] == integers[index - 1]:
continue

l, r = i + 1, len(nums) - 1
while l < r:
threeSum = a + nums[l] + nums[r]
if threeSum > 0:
r -= 1
elif threeSum < 0:
l += 1
left, right = index + 1, len(integers) - 1
while left < right:
if integers[left] + integers[right] < 0 - integers[index]:
left += 1
elif integers[left] + integers[right] > 0 - integers[index]:
right -= 1
else:
res.append([a, nums[l], nums[r]])
l += 1
r -= 1
while nums[l] == nums[l - 1] and l < r:
l += 1
return res
result.append([integers[index], integers[left], integers[right]]) # After a triplet is appended, we try our best to incease the numeric value of its first element or that of its second.
left += 1 # The other pairs and the one we were just looking at are either duplicates or smaller than the target.
right -= 1 # The other pairs are either duplicates or greater than the target.
# We must move on if there is less than or equal to one integer in between the two integers.
while integers[left] == integers[left - 1] and left < right:
left += 1 # The pairs are either duplicates or smaller than the target.
return result

0 comments on commit 86ba5cd

Please sign in to comment.