File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from itertools import combinations
2+
3+ class Solution :
4+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
5+ """
6+ time complexity : O(n^2)
7+ space complexity : O(1)
8+ """
9+ answer = []
10+ nums .sort ()
11+ n = len (nums )
12+
13+ for i in range (n ):
14+ #skipped if nums[i] == nums[i-1] to avoid duplicate triplets
15+ if i > 0 and nums [i ] == nums [i - 1 ]:
16+ continue
17+
18+ #search with two pointer
19+ left , right = i + 1 , n - 1
20+
21+ while left < right :
22+ total = nums [left ] + nums [i ] + nums [right ]
23+ if total == 0 :
24+ answer .append ([nums [left ], nums [i ], nums [right ]])
25+
26+ #move the pointers past duplicates
27+ while left < right and nums [left ] == nums [left + 1 ]:
28+ left += 1
29+ while left < right and nums [right ] == nums [right - 1 ]:
30+ right -= 1
31+
32+ left += 1
33+ right -= 1
34+ elif total < 0 :
35+ left += 1
36+ else :
37+ right -= 1
38+
39+ return answer
You can’t perform that action at this time.
0 commit comments