238 - Product Of Array Except Self
#medium
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n)
time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// 需考慮一個0及多個0的狀況
int all_p = 1;
int zero_nums = 0;
int zero_index = -1;
vector<int> result;
for ( int i = 0; i < nums.size(); i++ ) {
if ( nums[i] == 0 ) {
zero_nums++;
zero_index = i;
}
else all_p *= nums[i];
}
if ( zero_nums == 0 ) {
for ( int i = 0; i < nums.size(); i++ ) {
result.push_back( all_p / nums[i] );
}
}
else if ( zero_nums == 1 ) {
for ( int i = 0; i < nums.size(); i++ ) {
if ( i == zero_index ) result.push_back( all_p );
else result.push_back( 0 );
}
}
else {
for ( int i = 0; i < nums.size(); i++ ) {
result.push_back( 0 );
}
}
return result;
}
};