Leetcode238. Product of Array Except Self

Leetcode238. 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]

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

思路

使用左边乘积和右边乘积进行计算。

给定数组[2、3、4、5],对于数字4来说它的结果是2 * 3 * 5,即位于4左边的乘积2*3乘上位于4右边的乘积5。用这个思想我们遍历两边nums[]数组,记录下每个元素的左右乘积。

Numbers:     2    3    4     5
Lefts:            2  2*3 2*3*4
Rights:  3*4*5  4*5    5     

用1填充空余的位置

Numbers:     2    3    4     5
Lefts:       1    2  2*3 2*3*4
Rights:  3*4*5  4*5    5     1

时间复杂度O(n)

public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] res = new int[n];
    // Calculate lefts and store in res.
    int left = 1;
    for (int i = 0; i < n; i++) {
        if (i > 0)
            left = left * nums[i - 1];
        res[i] = left;
    }
    // Calculate rights and the product from the end of the array.
    int right = 1;
    for (int i = n - 1; i >= 0; i--) {
        if (i < n - 1)
            right = right * nums[i + 1];
        res[i] *= right;
    }
    return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章