Skip to content

Commit 60fe9ec

Browse files
authored
Create 238. Product of Array Except Self
1 parent 68fd9ef commit 60fe9ec

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

238. Product of Array Except Self

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public:
3+
vector<int> productExceptSelf(vector<int>& nums) {
4+
int prod = 1, zeroCnt = count(begin(nums), end(nums), 0);
5+
if(zeroCnt > 1) return vector<int>(size(nums)); // Case-1
6+
for(auto c : nums)
7+
if(c) prod *= c; // calculate product of all elements except 0
8+
for(auto& c : nums)
9+
if(zeroCnt) c = c ? 0 : prod; // Case-2
10+
else c = prod / c; // Case-3
11+
return nums;
12+
}
13+
};

0 commit comments

Comments
 (0)