LeetCode 238:Product of Array Except Self

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

给定一个具有n个元素的整数数组 nums (n>1),返回一个 output 数组,其中 output[i] 是 nums 数组中除了 nums[i] 以外其他所有元素的乘积。

不能使用划分,并且时间复杂度为O(n)。

例如,给定数组元素 [1,2,3,4] ,应当返回数组 [24,12,8,6]

提高:

你的答案能保证固定的空间复杂度吗?(注意:输出的数组空间在空间复杂度计算中不算作额外空间)


这里我分了三种情况,即nums里面0的个数分别为0,1,2以上三种:当有0个0时,求所有元素的乘积,每个元素再除当前num[i]的值即可;当有1个0时,除了output[i]为所有元素除nums[i]的乘积之外,其余结果均为0;当有2个或2个以上时,所有元素均为0。不过这样做好像违反了题目中不能划分的要求。。。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int temp=1,i=0;
        int count=0,flag=0;
        vector<int> ans;
        for(i=0;i<nums.size();i++)
        {
            if(nums[i]==0)
            {
                count++;
                flag=i;
                if(count>1) break;
            }
            else temp*=nums[i];
        }
        if(count>1)
        {
            for(i=0;i<nums.size();i++)
                ans.push_back(0);
        }
        else
        {
            for(i=0;i<nums.size();i++)
            {
                if(count==1)
                {
                    if(i!=flag)
                    ans.push_back(0);
                    else ans.push_back(temp);
                }
                else ans.push_back(temp/nums[i]);
            }
        }
        return ans; 
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值