File tree Expand file tree Collapse file tree 1 file changed +15
-13
lines changed Expand file tree Collapse file tree 1 file changed +15
-13
lines changed Original file line number Diff line number Diff line change 1
- from typing import List
2
- from itertools import combinations
3
1
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 )
You can’t perform that action at this time.
0 commit comments