LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)

Posted nomasp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)相关的知识,希望对你有一定的参考价值。

翻译

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

不用分治并且在O(n)复杂度下解决这个问题。

例如,给定[1, 2, 3, 4],返回[24, 12, 8, 6]。

跟进:
你可以只在常量空间下完成它吗?
(备注:在空间复杂度计算时输出数组不作为额外空间。)

原文

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

分析

其实之前做过一道类似的题目,不过想不起来是哪题了。

看到题目的常量空间就想到和之前的一样,把所有元素的乘积保存起来,最后再一个一个除就好了不是吗?

然而有问题……

如果数组中有一个零叻?

假设其索引是index,那么output[index]就是其余所有元素的乘积,也就是不计算0的乘积。

output数组的其余所有元素都是0。

如果数组中有两个及以上零叻?

什么都不用说,直接初始化为0吧。

如果数组中没有0叻?

那还不谢天谢地了,直接一个一个除了保存到vector嘛。

代码

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int count = 0;
        int pro = 1;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 0)           count++;
            else            pro *= nums[i];
        }       
        if (count == 1) {
            vector<int> res;
            for (int i = 0; i < nums.size(); i++) {
                if (nums[i] == 0)               res.push_back(pro);
                else                res.push_back(0);
            }
            return res;
        }
        else if (count >= 2) {
            vector<int> res(nums.size());
            return res;
        }
        else {
            vector<int> res;
            for (int i = 0; i < nums.size(); i++)
                res.push_back(pro / nums[i]);
            return res;
        }       
    }
};

以上是关于LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 238. Product of Array Except Self (Python版)

LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)

leetcode-Product of Array Except Self-238

Leetcode 238 Product of Array Except Self 时间O(n)和空间O解法

Leetcode 238. Product of Array Except Self

[LeetCode] 238. Product of Array Except Self