Skip to content

Commit 6177297

Browse files
Refactor : 3sum
1 parent 376c8c4 commit 6177297

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

3sum/printjin-gmailcom.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1-
from typing import List
2-
from itertools import combinations
31
class Solution:
4-
def threeSum(self, nums):
5-
res = set()
6-
n = len(nums)
7-
for i in range(n):
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]
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
triplets = set()
4+
nums.sort()
5+
for i in range(len(nums) - 2):
6+
low, high = i + 1, len(nums) - 1
7+
while low < high:
8+
three_sum = nums[i] + nums[low] + nums[high]
9+
if three_sum < 0:
10+
low += 1
11+
elif three_sum > 0:
12+
high -= 1
13+
else:
14+
triplets.add((nums[i], nums[low], nums[high]))
15+
low, high = low + 1, high - 1
16+
return list(triplets)

0 commit comments

Comments
 (0)