2p? solution using sets
This commit is contained in:
parent
5f98d05a8e
commit
07b46554a3
@ -3,7 +3,7 @@
|
||||
# neetcode 2024
|
||||
# 3sum
|
||||
|
||||
def solution(nums: list[int]) -> list[list[int]]:
|
||||
def solution0(nums: list[int]) -> list[list[int]]:
|
||||
if len(nums) < 3:
|
||||
return []
|
||||
if len(nums) == 3 and sum(nums) == 0:
|
||||
@ -25,6 +25,26 @@ def solution(nums: list[int]) -> list[list[int]]:
|
||||
triples.extend(comb(nums[p + 1:], nums[p]))
|
||||
return triples
|
||||
|
||||
|
||||
def solution(nums: list[int]) -> list[list[int]]:
|
||||
if len(nums) < 3:
|
||||
return []
|
||||
if len(nums) == 3:
|
||||
if sum(nums) == 0: return [nums]
|
||||
else: return []
|
||||
|
||||
r = []
|
||||
s = []
|
||||
for p0 in range(len(nums)):
|
||||
for p1 in range(p0 + 1, len(nums)):
|
||||
inverse = -1 * (nums[p0] + nums[p1])
|
||||
if inverse in set(nums[p1+1:]) and set({nums[p0], nums[p1], inverse}) not in s:
|
||||
r.append([nums[p0], nums[p1], inverse])
|
||||
s.append({nums[p0], nums[p1], inverse})
|
||||
|
||||
return list(map(lambda ss: list(ss), r))
|
||||
|
||||
|
||||
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]) == [])
|
||||
|
Loading…
x
Reference in New Issue
Block a user