【LeetCode】238. Product of Array Except Self

时间:2021-06-08 07:01:18

Product of Array Except Self

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

就是用减法实现除法。

注意零的处理。

class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int size = nums.size();
vector<int> ret(size, );
long long product = ;
int countZero = ;
int ind = -; // 0-index for(int i = ; i < size; i ++)
{
if(nums[i] == )
{
countZero ++;
ind = i;
}
} //special case for 0
if(countZero == )
{//no zero
for(int i = ; i < size; i ++)
product *= nums[i];
for(int i = ; i < size; i ++)
ret[i] = mydivide(product, nums[i]);
}
else if(countZero == )
{//1 zero
for(int i = ; i < size; i ++)
{
if(i != ind)
product *= nums[i];
}
ret[ind] = product; //others are 0s
}
else
{//2 or more zeros
; //all 0s
} return ret;
}
int mydivide(long long product, int divisor)
{// guaranteed that divisor is not 0
int sign = ;
if((product < ) ^ (divisor < ))
sign = -;
if(product < )
product = -product;
if(divisor < )
divisor = -divisor;
//to here, product and divisor are positive
int ret = ;
while(true)
{
int part = ; //part quotient
int num = divisor;
while(product > num)
{
num <<= ;
part <<= ;
}
if(product == num)
{
ret += part;
return sign * ret;
}
else
{
num >>= ;
part >>= ;
ret += part;
product -= num;
}
}
}
};

【LeetCode】238. Product of Array Except Self