1
+ """
2
+ Time: O(N^2)
3
+ Space: O(1)
4
+
5
+ First of all, we need to sort the list, so that it is easier to know where to move the pointers.
6
+ (Keep in mind that sorting takes O(NLogN) of time, but since judging from the problem this solution might takes at least O(N^2), so it is ok to sort.)
7
+
8
+ Now, we have 3 unique pointers at the list. i, j, k, where i<j<k.
9
+ For a given i, set j at i+1 and k at the rightest.
10
+
11
+ If the sum is too large, our only option is to move k left, so we can find smaller sum.
12
+ If the sum is too small, our only option is to move j right, so we can find larger sum.
13
+ If the sum is what we want, add it to the ans.
14
+
15
+ [0] we need to skip the num that is the same as the last one to remove duplicate. This is actually the hardest part of the problem.
16
+ [1] if nums[i] is larger than 0, we can stop, since nums[i] and nums[k] are surely larger than nums[i]
17
+ """
18
+ class Solution :
19
+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
20
+ ans = []
21
+ nums .sort ()
22
+
23
+ for i in range (len (nums )):
24
+ if 0 < i and nums [i ]== nums [i - 1 ]: continue #[0]
25
+ if nums [i ]> 0 : break #[1]
26
+
27
+ j , k = i + 1 , len (nums )- 1
28
+ while j < k :
29
+ if nums [i ]+ nums [j ]+ nums [k ]> 0 :
30
+ k -= 1
31
+ elif nums [i ]+ nums [j ]+ nums [k ]< 0 :
32
+ j += 1
33
+ else :
34
+ ans .append ((nums [i ], nums [j ], nums [k ]))
35
+ while 0 < k - 1 and nums [k - 1 ]== nums [k ]: k -= 1 #[0]
36
+ while j + 1 < len (nums ) and nums [j + 1 ]== nums [j ]: j += 1 #[0]
37
+ k -= 1
38
+ j += 1
39
+
40
+ return ans
0 commit comments