https://leetcode.com/problems/product-of-array-except-self/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
prefix : 왼쪽으로부터의 누적곱
suffix : 오른쪽으로부터의 누적곱
이걸 이용해서 i에서의 answer은 i -1 까지의 prefix와 i + 1까지의 suffix의 곱으로 구하면 된다.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
result = [1] * len(nums)
prefix = suffix = 1
for i in range(1, len(nums)):
prefix *= nums[i - 1]
suffix *= nums[-i]
result[i] *= prefix
result[-i - 1] *= suffix
return result
사실상 O(N)
'코딩 테스트 및 알고리즘 > Grind 75 (Blind 75 Leetcode Questions)' 카테고리의 다른 글
| Array : Merge Intervals (0) | 2024.02.17 |
|---|---|
| Array: Combination Sum (0) | 2024.02.17 |
| Array : Non-overlapping Intervals (0) | 2024.02.15 |
| LinkedList : Reorder List (0) | 2024.01.23 |
| LinkedList : Sort List (0) | 2024.01.21 |