Array - 238. Product of Array Except Self

2020-09-23 17:06:53 浏览数 (2)

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:

代码语言:javascript复制
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;
    }
}

0 人点赞