【LeetCode】- Product of Array Except Self(除了自己的其它的数相乘)

1、题目描述

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、问题关键:

  • 用一个数组,从左到右,先记录第i个元素左边元素的乘积,再从右到 左乘上右边元素的乘积。

4、C++代码:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> res(nums.size());
        for (int i = 0, t = 1;i < nums.size(); i ++) {
            res[i] = t;//记录左边元素的乘积。
            t *= nums[i];
        }
        for (int i = nums.size() - 1, t = 1; i >= 0; i --) {
            res[i] *= t;//再乘上右边元素的乘积。
            t *= nums[i];
        }
        return res;
    }
};
    原文作者:邓泽军_3679
    原文地址: https://www.jianshu.com/p/de0a5ce675ed
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞