60ms C++ Solution


  • 0
    S
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            int prod = 1;
            int zerocount =0;
            for(int i = 0;i< nums.size();i++){
                if(nums[i] == 0) zerocount++;
                else prod *= nums[i];
            }
            vector<int> res;
            if(zerocount>1){
                for(int i=0;i<nums.size();i++){
                    res.push_back(0);
                }
                return res;
            }
            if(zerocount == 1){
                for(int i =0;i<nums.size();i++){
                    if(nums[i] == 0){
                        res.push_back(prod);
                    }else res.push_back(0);
                }
            }else{
                for(int i =0;i<nums.size();i++){
                    res.push_back(prod/nums[i]);
                }
            }
            
            return res;
        }
    };

  • 0
    J

    You used divide in the final loop, however, the question says you cannot use divide operation.
    Your zero count ideas is good.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.