leet-code/product-of-array-except-self/sol.go

19 lines
323 B
Go
Raw Normal View History

2021-11-05 12:53:13 +00:00
package main
// Time: O(n)
// Space: O(1)
func productExceptSelf(nums []int) []int {
l := len(nums)
answer := make([]int, l)
answer[0] = 1
for idx := 1; idx < l; idx++ {
answer[idx] = answer[idx-1] * nums[idx-1]
}
m := 1
for idx := l - 1; idx >= 0; idx-- {
answer[idx] *= m
m *= nums[idx]
}
return answer
}