Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length = len(nums)
# Initialize the output array with 1s
output = [1] * length
# Left pass: calculate the product of all elements to the left of each index
left_product = 1
for i in range(length):
output[i] = left_product
left_product *= nums[i] # Update left_product to include nums[i]
# Right pass: calculate the product of all elements to the right of each index
right_product = 1
for i in range(length - 1, -1, -1):
output[i] *= right_product # Multiply with the accumulated right product
right_product *= nums[i] # Update right_product to include nums[i]
return output
포인터를 쓰는 줄 알았는데 뭔가 좀 안되는 것 같아서 흠 어쩌지 하다가 결국 솔루션을 봤는데 pass란 걸 써서 하게 된다는 걸 알게 됐다. 두 개가 뭔 차인가 싶었는데 간단하게 말하면. pass의 경우 cumulative한 동작들을 수행할 때, 특히 array나 list를 갖고 쭈르륵할 때 사용되고, 포인터의 경우 인덱스를 갖고서 (투포인터라면 리스트의 양끝에서) 서로가 만나는 지점까지 가거나 어느 특정한 요소를 타겟해서 무언가 계산을 수행할 때 사용된다.
흠 몰랐던 거여서 아쉬운 점도 있지만 이런 방식으로도 계산을 할수 있다란 점에서 좀 재밌었음.