Leetcode - Trapping Rain Water
Leetcode - Best Time to Buy and Sell Stock II

Leetcode - Product of Array Except Self

violet posted @ Mar 30, 2020 02:56:48 AM in 算法 with tags Algorithm Golang array , 266 阅读

https://leetcode.com/problems/product-of-array-except-self/

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

Note: Please solve it without division and in O(n).

 

Code shows everythings.

func productExceptSelf(nums []int) []int {
    result := make([]int, len(nums))
    result[0] = 1
    for i := 1; i < len(nums); i++ {
        result[i] = result[i-1] * nums[i-1]
    }
    
    right := 1
    for i := len(nums)-1; i >= 0; i-- {
        result[i] *= right
        right *= nums[i]
    }
    
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter