238. Product of Array Except Self

package LeetCode_238

/**
 * 238. Product of Array Except Self
 * https://leetcode.com/problems/product-of-array-except-self/description/
 * 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).

Follow up:
Could you solve it with constant space complexity?
(The output array does not count as extra space for the purpose of space complexity analysis.)
 * */
class Solution {
    /*
    * solution 1: prefix_array and suffix_array, Time complexity:O(n), Space complexity:O(n);
    * */
    fun productExceptSelf(nums: IntArray): IntArray {
        val n = nums.size

        val prefixArray = IntArray(n,{1})
        val suffixArray = IntArray(n,{1})

        var prefixProduct = 1
        for (i in 1 until n) {
            prefixProduct *= nums[i-1]
            prefixArray[i] = prefixProduct
        }

        for (i in n - 1 downTo 1) {
            suffixArray[i-1] = suffixArray[i] * nums[i]
        }

        val result = IntArray(n)
        for (i in 0 until n){
            result[i] = prefixArray[i] * suffixArray[i]
        }

        return result
    }
}

 

posted @ 2020-08-06 01:20  johnny_zhao  阅读(66)  评论(0编辑  收藏  举报