LeetCode Product of Array Except Self

来源:互联网 发布:360水滴破解软件 编辑:程序博客网 时间:2024/06/05 09:56

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

Subscribe to see which companies asked this question

这道题要求除了自己以外的所有其他元素的和,这里的思路是先遍历数组一遍求出所有非0元素的积,并且记录当前数组中0的个数。然后对每个元素检查,如果当前元素等于0并且没有其他元素为0 ,那么积为其他非0元素的积,如果除了当前元素还有其他0,那么积为0;如果当前元素非0但是有其他元素为0的,那么当前元素的积为0;如果当前元素非0而且其他元素也非0,那么就用总积除以当前元素。

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


0 0
原创粉丝点击