【LeetCode】238. 除自身以外数组的乘积 结题报告 (C++)

原题地址:https://leetcode-cn.com/problems/product-of-array-except-self/submissions/

题目描述:

给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。

示例:

输入: [1,2,3,4]
输出: [24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。

进阶:
你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)

解题方案:

数组题型,要求不能用除法,而且不能有额外的空间。

非常简单,我们可以遍历nums,在遍历的过程中将对应元素累乘,例如

1  2  3  4
1  1  2  6
这样我们就得到了对应元素左边所有元素的乘积。然后我们反向遍历nums,做相同操作即可。

1  2  3  4
24 12 4  1
再将两个结果相乘即可。

1  2  3  4
24 12 8  6
这样的话,就有额外的空间生成。其实,只需做一点调整就能解决问题:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> ans;
        if(nums.size() == 0)
            return ans;
        ans.push_back(1);
        for(int i = 1; i < nums.size(); i ++){
            ans.push_back(ans[i -1] * nums[i - 1]);
        }
        int tmp = nums[nums.size() - 1];
        for(int i = nums.size() - 2; i >= 0; i --){
            ans[i] *= tmp;
            tmp *= nums[i];
        }
        
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32805671/article/details/84563232