File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 0015. 3Sum
2
+
3
+ * Difficulty: medium
4
+ * Link: https://leetcode.com/problems/3sum/
5
+ * Topics: Array-String, Multiple-Pointers
6
+
7
+ # Clarification
8
+
9
+ 1 . Check the inputs and outputs
10
+ - INPUT: List[ int]
11
+ - OUTPUT: List [ List[ int] ]
12
+
13
+ # Naive Solution
14
+
15
+ ### Thought Process
16
+
17
+ 1 . sort the nums
18
+ 2 . extend two sum
19
+
20
+ ``` python
21
+ [- 1 ,0 ,1 ,2 ,- 1 ,- 4 ]
22
+ ^ i j
23
+ ```
24
+
25
+ - Implement
26
+
27
+ ```python
28
+ class Solution :
29
+ def threeSum (self , nums : List[int ]) -> List[List[int ]]:
30
+ result = []
31
+ nums.sort()
32
+ for i in range (0 , len (nums) - 2 ):
33
+ if i > 0 and nums[i] == nums[i- 1 ]:
34
+ continue
35
+ l = i + 1
36
+ r = len (nums) - 1
37
+ while l < r:
38
+ s = nums[i] + nums[l] + nums[r]
39
+ if s > 0 :
40
+ r -= 1
41
+ elif s < 0 :
42
+ l += 1
43
+ else :
44
+ result.append((nums[i], nums[l], nums[r]))
45
+ while l < r and nums[l] == nums[l + 1 ]:
46
+ l += 1
47
+ while l < r and nums[r] == nums[r - 1 ]:
48
+ r -= 1
49
+ l += 1
50
+ r -= 1
51
+
52
+ return result
53
+ ```
54
+
55
+
56
+ # ## Complexity
57
+
58
+ - Time complexity: $ O(n^ 2 )$
59
+ - Space complexity:$ O(1 )$
You can’t perform that action at this time.
0 commit comments