forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#2372 from ksfkwan/patch-1
Update 0015-3sum.py
- Loading branch information
Showing
1 changed file
with
23 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |