File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ # idea: sorting + two pointer
2+ # The idea was straightforward, but remove the duplication logic was the tricky.
3+
4+ class Solution :
5+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
6+ nums .sort ()
7+ n = len (nums )
8+ answer = []
9+
10+ for i in range (n ):
11+ if i > 0 and nums [i ] == nums [i - 1 ]:
12+ continue
13+
14+ left , right = i + 1 , n - 1
15+
16+ while left < right :
17+ s = nums [i ] + nums [left ] + nums [right ]
18+ if s == 0 :
19+ answer .append ([nums [i ], nums [left ], nums [right ]])
20+ while left < right and nums [left ] == nums [left + 1 ]:
21+ left += 1
22+ while left < right and nums [right ] == nums [right - 1 ]:
23+ right -= 1
24+ left += 1
25+ right -= 1
26+ elif s < 0 :
27+ left += 1
28+ else :
29+ right -= 1
30+ return answer
31+
32+
Original file line number Diff line number Diff line change 1+ # idea: O(n) - There is no multiplication calculate it as O(1) / addition is possible
2+
3+ class Solution :
4+ def productExceptSelf (self , nums : List [int ]) -> List [int ]:
5+ length = len (nums )
6+ answer = [1 ] * length
7+
8+ prefix ,suffix = 1 ,1
9+ for i in range (length ):
10+ answer [i ] = prefix
11+ prefix *= nums [i ]
12+ for j in range (length - 1 , - 1 , - 1 ):
13+ answer [j ] *= suffix
14+ suffix *= nums [j ]
15+ return answer
16+
17+
You can’t perform that action at this time.
0 commit comments