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嘛。

代码

C Plus Plus

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;
        }       
    }
};

Java

    public int[] productExceptSelf(int[] nums) {
        int count = 0, totalproduct = 1;
        int[] product = new int[nums.length];
        for (int i : nums) {
            if (i == 0) count++;
            else totalproduct *= i;
        }
        if (count >= 2) {
            return product;
        } else if (count == 1) {
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 0) product[i] = totalproduct;
            }
        } else {
            for (int i = 0; i < nums.length; i++) {
                product[i] = totalproduct / nums[i];
            }
        }
        return product;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值