Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Bugfix][Python][0015-3sum] Revert wrong commit #2505

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 24 additions & 23 deletions python/0015-3sum.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
class Solution:
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:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()

for i, a in enumerate(nums):
# Skip positive integers
if a > 0:
break
if index > 0 and integers[index] == integers[index - 1]:

if i > 0 and a == nums[i - 1]:
continue
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

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
else:
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
res.append([a, nums[l], nums[r]])
l += 1
r -= 1
while nums[l] == nums[l - 1] and l < r:
l += 1

return res