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:

    1. Input: [1,2,3,4]
    2. 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.)


    题意

    给定一个数组nums,要求返回一个新数组output,满足以下条件:
    238. Product of Array Except Self (M) - 图1
    限制时间复杂度为238. Product of Array Except Self (M) - 图2,且不能使用除法。

    思路

    output[i]相当于在nums中将nums[i]左边所有数和nums[i]右边所有数累乘。因此可以采取类似于动态规划的操作:先从左到右遍历一遍nums,记录当前位置所有左侧数字之积;再从右到左遍历一遍nums,记录当前位置所有右侧数字之积,将两者相乘后得到的就是output。可以只使用一个output数组来达到238. Product of Array Except Self (M) - 图3的空间复杂度。

    0 1 2 3
    nums 1 2 3 4
    左右遍历 1 1 2 6
    右左遍历 24 12 4 1
    Output 24 12 8 6

    代码实现

    1. class Solution {
    2. public int[] productExceptSelf(int[] nums) {
    3. int[] output = new int[nums.length];
    4. int leftProduct = 1;
    5. for (int i = 0; i < nums.length; i++) {
    6. output[i] = i == 0 ? 1 : (leftProduct *= nums[i - 1]);
    7. }
    8. int rightProduct = 1;
    9. for (int i = nums.length - 1; i >= 0; i--) {
    10. output[i] = output[i] * (i == nums.length - 1 ? 1 : (rightProduct *= nums[i + 1]));
    11. }
    12. return output;
    13. }
    14. }