#Leetcode# 238. Product of Array Except Self

https://leetcode.com/problems/product-of-array-except-self/

 

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does notcount as extra space for the purpose of space complexity analysis.)

代码:

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

  

posted @ 2019-04-15 01:00  丧心病狂工科女  阅读(106)  评论(0编辑  收藏  举报