-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solved "239. Product of Array Except Self"
- Loading branch information
1 parent
58d4dd3
commit 15eca17
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
""" | ||
Constraints: | ||
1. 2 <= nums.length <= 10^5 | ||
2. -30 <= nums[i] <= 30 | ||
3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer | ||
Time Complexity: O(n) | ||
- λ°°μ΄μ λ λ² μννλ―λ‘ O(n) | ||
Space Complexity: O(1) | ||
- μΆλ ₯ λ°°μ΄(answer)μ μ μΈνλ©΄ μΆκ° 곡κ°μ΄ μμλ§νΌλ§ νμ(left, right λ³μ) | ||
νμ΄ λ°©λ²: | ||
1. answer λ°°μ΄μ 1λ‘ μ΄κΈ°ν (κ³±μ μμλ 1μ΄ μν₯μ μ£Όμ§ μμ) | ||
2. μΌμͺ½μμ μ€λ₯Έμͺ½μΌλ‘ μν: | ||
- answer[i]μ νμ¬κΉμ§μ left λμ κ°μ κ³±ν¨ | ||
- left *= nums[i]λ‘ λ€μμ μν΄ left κ°μ μ λ°μ΄νΈ | ||
3. μ€λ₯Έμͺ½μμ μΌμͺ½μΌλ‘ μν (range(n-1, -1, -1) μ¬μ©): | ||
- answer[i]μ νμ¬κΉμ§μ right λμ κ°μ κ³±ν¨ | ||
- right *= nums[i]λ‘ λ€μμ μν΄ right κ°μ μ λ°μ΄νΈ | ||
""" | ||
|
||
class Solution: | ||
def productExceptSelf(self, nums: List[int]) -> List[int]: | ||
n = len(nums) | ||
answer = [1] * n | ||
|
||
left = 1 | ||
for i in range(n): | ||
answer[i] *= left | ||
left *= nums[i] | ||
|
||
right = 1 | ||
for i in range(n-1, -1, -1): | ||
answer[i] *= right | ||
right *= nums[i] | ||
|
||
return answer |