My C++ code with 56ms


  • -4
    H
    class Solution {
    public:
      vector<int> productExceptSelf(vector<int>& nums) {
          if (nums.empty())
    		  return{};
    	  if (nums.size() == 2){
    		  swap(nums[0], nums[1]);
    		  return nums;
    	  }
    	  int productOfSum = 1, count = 0;
    	  for (int i = 0; i < nums.size(); ++i){
    		  if (nums[i] != 0)
    			  productOfSum *= nums[i];
    		  else
    			  count++; //count the zero in nums
    	  }
    	  if (count == nums.size()) //all are zero
    		  return nums;
    	  else if (count == 1){ //have one zero
    		  for (int i = 0; i < nums.size(); ++i){
    			  if (nums[i] == 0)
    				  nums[i] = productOfSum;
    			  else
    				  nums[i] = 0;
    		  }
    	  }
    	  else if (count > 1){ //more than one zero
    		  for (int i = 0; i < nums.size(); ++i){
    			  nums[i] = 0;
    		  }
    	  }
    	  else {
    		  for (int i = 0; i < nums.size(); ++i) //no zero
    			  nums[i] = productOfSum / nums[i];
    	  }
    	  return nums;
      }
    };
    

    Not a very nice code I think,but fast.


  • 0
    B

    the problem said: "Solve it without division and in O(n)".
    this algorithm uses division...


Log in to reply
 

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