Skip to content

Commit 43c3f4e

Browse files
add Three sum (#9177)
* add Three sum * add Three sum * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * update * update * update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * add documention --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 596d934 commit 43c3f4e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Diff for: maths/three_sum.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
https://en.wikipedia.org/wiki/3SUM
3+
"""
4+
5+
6+
def three_sum(nums: list[int]) -> list[list[int]]:
7+
"""
8+
Find all unique triplets in a sorted array of integers that sum up to zero.
9+
10+
Args:
11+
nums: A sorted list of integers.
12+
13+
Returns:
14+
A list of lists containing unique triplets that sum up to zero.
15+
16+
>>> three_sum([-1, 0, 1, 2, -1, -4])
17+
[[-1, -1, 2], [-1, 0, 1]]
18+
>>> three_sum([1, 2, 3, 4])
19+
[]
20+
"""
21+
nums.sort()
22+
ans = []
23+
for i in range(len(nums) - 2):
24+
if i == 0 or (nums[i] != nums[i - 1]):
25+
low, high, c = i + 1, len(nums) - 1, 0 - nums[i]
26+
while low < high:
27+
if nums[low] + nums[high] == c:
28+
ans.append([nums[i], nums[low], nums[high]])
29+
30+
while low < high and nums[low] == nums[low + 1]:
31+
low += 1
32+
while low < high and nums[high] == nums[high - 1]:
33+
high -= 1
34+
35+
low += 1
36+
high -= 1
37+
elif nums[low] + nums[high] < c:
38+
low += 1
39+
else:
40+
high -= 1
41+
return ans
42+
43+
44+
if __name__ == "__main__":
45+
import doctest
46+
47+
doctest.testmod()

0 commit comments

Comments
 (0)