88-Product of Array

来源:互联网 发布:贱人就是矫情网络歌曲 编辑:程序博客网 时间:2024/05/29 10:55

-238. Product of Array Except Self My Submissions QuestionEditorial Solution
Total Accepted: 46367 Total Submissions: 107341 Difficulty: Medium
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].

考虑到特殊情况:
有一个0,有多个0

class Solution {public:    vector<int> productExceptSelf(vector<int>& nums) {        int n= nums.size();        //if(n==0)return nums;        vector<int> res(n,0);        long long allProduct =1;        int zero_num = 0;        for(int &i:nums)            if(i!=0)allProduct*=i;            else ++zero_num;        if(zero_num>1)return res;//如果序列中有超过一个0,返回全0        for(int j=0;j<n;++j)            if(nums[j]!=0&&zero_num==0)res[j]=allProduct/nums[j];//如果当前元素不为0,且没0元素            else if(nums[j]==0&&zero_num==1) res[j]=allProduct;  //如果当前元素就为0,则等于allProduct        return res;    }};
0 0