File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # Leetcode 15. 3Sum
3
+
4
+ use **two pointers** to solve this problem.
5
+
6
+ ## Time and Space Complexity
7
+
8
+ ```
9
+ TC: O(n^2)
10
+ SC: O(1)
11
+ ```
12
+
13
+ ### TC is O(n^2):
14
+ - sorting the list = O(n log n)
15
+ - iterating through the list and using two pointers to find the sum of three numbers. = O(n^2)
16
+
17
+ ### SC is O(1):
18
+ - sorting in place = O(1)
19
+ '''
20
+
21
+ class Solution :
22
+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
23
+ nums .sort () # TC: O(n log n), SC: O(1)
24
+ result = [] # result are part of the output => do not count toward auxiliary (extra) space.
25
+
26
+ for i in range (len (nums )): # TC: O(n^2)
27
+ if i > 0 and nums [i ] == nums [i - 1 ]:
28
+ continue
29
+
30
+ j = i + 1
31
+ k = len (nums ) - 1
32
+ while j < k :
33
+ currSum = nums [i ] + nums [j ] + nums [k ]
34
+
35
+ if currSum < 0 :
36
+ j += 1
37
+ elif currSum > 0 :
38
+ k -= 1
39
+ else :
40
+ result .append ([nums [i ], nums [j ], nums [k ]])
41
+
42
+ while j < k and nums [j ] == nums [j + 1 ]:
43
+ j += 1
44
+ while j < k and nums [k ] == nums [k - 1 ]:
45
+ k -= 1
46
+
47
+ j += 1
48
+ k -= 1
49
+
50
+ return result
You can’t perform that action at this time.
0 commit comments