Skip to content

Commit af1d46c

Browse files
Refactor : 3sum
1 parent cefa7c9 commit af1d46c

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

3sum/printjin-gmailcom.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
from typing import List
2+
from itertools import combinations
23
class Solution:
34
def threeSum(self, nums):
5+
res = set()
46
n = len(nums)
5-
result = set()
67
for i in range(n):
7-
for j in range(i + 1, n):
8-
for k in range(j + 1, n):
9-
if nums[i] + nums[j] + nums[k] == 0:
10-
triplet = tuple(sorted([nums[i], nums[j], nums[k]]))
11-
result.add(triplet)
12-
return [list(t) for t in result]
8+
a = nums[i]
9+
rest = nums[:i] + nums[i+1:]
10+
for comb in combinations(rest, 2):
11+
if sum(comb) == -a:
12+
triplet = tuple(sorted([a, *comb]))
13+
res.add(triplet)
14+
return [list(t) for t in res]

0 commit comments

Comments
 (0)