Skip to content

Commit 86ba5cd

Browse files
authored
Merge pull request neetcode-gh#2372 from ksfkwan/patch-1
Update 0015-3sum.py
2 parents f16617a + fb06d5f commit 86ba5cd

File tree

1 file changed

+23
-23
lines changed

1 file changed

+23
-23
lines changed

python/0015-3sum.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
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-
# Skip positive integers
8-
if a > 0:
2+
def ThreeSum(self, integers):
3+
"""
4+
:type integers: List[int]
5+
:rtype: List[List[int]]
6+
"""
7+
integers.sort()
8+
result = []
9+
for index in range(len(integers)):
10+
if integers[index] > 0:
911
break
10-
11-
if i > 0 and a == nums[i - 1]:
12+
if index > 0 and integers[index] == integers[index - 1]:
1213
continue
13-
14-
l, r = i + 1, len(nums) - 1
15-
while l < r:
16-
threeSum = a + nums[l] + nums[r]
17-
if threeSum > 0:
18-
r -= 1
19-
elif threeSum < 0:
20-
l += 1
14+
left, right = index + 1, len(integers) - 1
15+
while left < right:
16+
if integers[left] + integers[right] < 0 - integers[index]:
17+
left += 1
18+
elif integers[left] + integers[right] > 0 - integers[index]:
19+
right -= 1
2120
else:
22-
res.append([a, nums[l], nums[r]])
23-
l += 1
24-
r -= 1
25-
while nums[l] == nums[l - 1] and l < r:
26-
l += 1
27-
return res
21+
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.
22+
left += 1 # The other pairs and the one we were just looking at are either duplicates or smaller than the target.
23+
right -= 1 # The other pairs are either duplicates or greater than the target.
24+
# We must move on if there is less than or equal to one integer in between the two integers.
25+
while integers[left] == integers[left - 1] and left < right:
26+
left += 1 # The pairs are either duplicates or smaller than the target.
27+
return result

0 commit comments

Comments
 (0)