wip: 3 pointers 3sum
This commit is contained in:
parent
f52b64ba4f
commit
5f98d05a8e
33
medium/3sum.py
Normal file
33
medium/3sum.py
Normal file
@ -0,0 +1,33 @@
|
||||
#!/usr/bin/python
|
||||
# yigid balaban <fyb@fybx.dev>
|
||||
# neetcode 2024
|
||||
# 3sum
|
||||
|
||||
def solution(nums: list[int]) -> list[list[int]]:
|
||||
if len(nums) < 3:
|
||||
return []
|
||||
if len(nums) == 3 and sum(nums) == 0:
|
||||
return [nums]
|
||||
|
||||
nums = sorted(nums)
|
||||
triples = []
|
||||
def comb(what: list[int], head: int):
|
||||
mtriples = []
|
||||
for p0 in range(0, len(what) + 1):
|
||||
for p1 in range(p0, len(what)):
|
||||
if p1 != p0 and head + what[p0] + what[p1] == 0:
|
||||
triple = sorted([head, what[p0], what[p1]])
|
||||
if triple not in triples and triple not in mtriples:
|
||||
mtriples.append(triple)
|
||||
return mtriples
|
||||
|
||||
for p in range(len(nums) - 3):
|
||||
triples.extend(comb(nums[p + 1:], nums[p]))
|
||||
return triples
|
||||
|
||||
print(solution([0,0]) == [])
|
||||
print(solution([-1,0,1,2,-1,-4]), solution([-1,0,1,2,-1,-4]) == [[-1,-1,2],[-1,0,1]])
|
||||
print(solution([0,1,1]) == [])
|
||||
print(solution([0,0,0]) == [[0,0,0]])
|
||||
print(solution([0,0,0,0]) == [[0,0,0]])
|
||||
|
Loading…
x
Reference in New Issue
Block a user