Array - 238. Product of Array Except Self

时间:2022-07-25
本文章向大家介绍Array - 238. Product of Array Except Self,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

238. 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 numsexcept nums[i].

Example:

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

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

思路:

当前位置的左边全部相乘,右边全部相乘,然后全乘起来就可以。乘右边的时候可以倒着计算就可以两边循环就得出结果。

代码:

java:

class Solution {

    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] res = new int[len];
        res[0] = 1;
        // left multi
        for (int i = 1; i < len; i++) {
            res[i] = res[i-1] * nums[i-1];
        }
            
        // right multi
        int right = 1;
        for (int i = len  -1; i >= 0; i--) {
            res[i] *= right;
            right *= nums[i];
        }
        
        return res;
    }
}