Product of Array Except Self

406 篇文章 0 订阅
406 篇文章 0 订阅

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

给定n个整数的数组,其中n> 1,返回一个数组输出,使得output [i]等于除nums [i]之外的所有nums元素的乘积。

注意:
请在没有除法的情况下解决,并在O(n)中解决。

跟进:
你能用恒定的空间复杂度解决它吗? (出于空间复杂度分析的目的,输出数组不算作额外空间。)

2,题目思路

对于这道题,所要求解的目标是给定一个数组,返回对应位,除了该位之外的所有的累加乘积。题中的例子也已经非常明确了。

如果我们使用暴力求解的方法是非常简单的,对每一位都进行一次遍历即可。

但是, 这种方法的时间消耗太大,不是很好的方法。

因此,对于这种需要遍历整个数组并返回除了自己之外的计算结果的题目,我们可以利用从前往后、从后往前的策略,来对整个数组实现遍历并计算乘积的功能。

在从前往后遍历时,我们利用一个变量记录从开始到当前位置的累加和。

从后往前也是一样,记录乘积。

具体算法过程见第三部分。

3,代码实现

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
    int numsLen = nums.size();
	vector<int> res (numsLen, 1);
	int productFront = 1; 	//从前往后
	int productBack = 1;	//从后往前

	for (int i = 0; i < numsLen; i++)
	{
		res[i] = res[i] * productFront;
		productFront = productFront*nums[i];
	}

	for (int i = numsLen - 1; i >= 0; i--)
	{
		res[i] = res[i] * productBack;
		productBack = productBack * nums[i];
	}
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值