-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15. 3Sum.py
29 lines (29 loc) · 943 Bytes
/
15. 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
28
29
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = set()
n, p, z = [], [], []
for num in nums:
if num > 0:
p.append(num)
elif num < 0:
n.append(num)
else:
z.append(num)
N, P = set(n), set(p)
if z:
for num in P:
if -1*num in N:
res.add((-1*num, 0, num))
if len(z) >= 3:
res.add((0,0,0))
for i in range(len(n)):
for j in range(i+1,len(n)):
target = -1*(n[i]+n[j])
if target in P:
res.add(tuple(sorted([n[i],n[j],target])))
for i in range(len(p)):
for j in range(i+1,len(p)):
target = -1*(p[i]+p[j])
if target in N:
res.add(tuple(sorted([p[i],p[j],target])))
return res