File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ # three sum | leetcode 15 | https://leetcode.com/problems/3sum/
2
+ # - sorted; nested loop; outer loop for first element
3
+ # - inner loop for two sum on rest of list
4
+ # - avoid duplicates by shifting window till last occurrence
5
+
6
+ class Solution :
7
+ def threeSum (self , nums : list [int ]) -> list [list [int ]]:
8
+ nums .sort ()
9
+ N = len (nums )
10
+ triplets = []
11
+ for i in range (N ):
12
+ if i > 0 and nums [i ] == nums [i - 1 ]:
13
+ continue
14
+
15
+ ptrL = i + 1
16
+ ptrR = N - 1
17
+ while ptrL < ptrR :
18
+ s = nums [i ] + nums [ptrL ] + nums [ptrR ]
19
+ if s > 0 :
20
+ ptrR -= 1
21
+ elif s < 0 :
22
+ ptrL += 1
23
+ else :
24
+ triplets .append ([nums [i ], nums [ptrL ], nums [ptrR ]])
25
+ ptrL += 1
26
+ while nums [ptrL ] == nums [ptrL - 1 ] and ptrL < ptrR :
27
+ ptrL += 1
28
+
29
+ return triplets
You can’t perform that action at this time.
0 commit comments