文章 224
评论 6
浏览 200766
Array - 238. Product of Array Except Self

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;
    }
}

标题:Array - 238. Product of Array Except Self
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/24/1561390226796.html

Nothing just happens, it's all part of a plan.

取消