LN : leetcode 238 Product of Array Except Self

lc 238 Product of Array Except Self


238 Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:

Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

Accepted

本来可以先求出所有元素的积,再以O(n)的复杂度遍历除得答案,但题目要求不能使用除法。

我们知道对于答案的第一位一定等于从后往前乘,直至乘到它为止,不包括它自身;而答案的最后一位一定等于从前往后乘,直至乘到它为止,不包括它自身。所以我们定义两个变量,frombegin代表从前往后的积,fromlast代表从后往前的积。

通过一层for循环,对于每一次迭代都对当前元素乘上frombegin,对其对称位乘上fromlast,这样最终就可以很神奇地得到除去自身外的其他位的乘积。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size(), frombegin = 1, fromlast = 1;
        vector<int> ans(n,1);
        for (int i = 0; i < n; i++) {
            ans[i] *= frombegin;
            frombegin *= nums[i];
            ans[n-1-i] *= fromlast;
            fromlast *= nums[n-1-i];
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/renleimlj/p/7711299.html