Leetcode 0238: 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).

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.)

Time complexity: O(n)
1、以一次遍历求出数组res为前缀积,即res[i]维护的是[0,i-1]的前缀积。
2、用suffixProd变量来存储后缀积,从后往前遍历到第i为时suffixProd 为[i+1,n]的后缀积。则每次 suffixProd * res就是 对应第i位的答案。

例子数组 [1, 2, 3, 4]
前缀积 : 1, 1, 2, 6
后缀积:24, 12,4,1

class Solution {
    
    
    public int[] productExceptSelf(int[] nums) {
    
    
        int n = nums.length;
        int[] res = new int[n];
        res[0] = 1;
        for(int i = 1; i < n;i++){
    
    
            res[i] = res[i-1]*nums[i-1];
        }
        int suffixProd = 1;
        for(int i = n-1; i >= 0;i--){
    
    
            res[i] = suffixProd*res[i];
            suffixProd *= nums[i];
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113967234