forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0015-3sum.py
27 lines (27 loc) · 1.42 KB
/
0015-3sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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:
break
if index > 0 and integers[index] == integers[index - 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
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