-
Notifications
You must be signed in to change notification settings - Fork 9
/
ProductExceptSelf.cpp
36 lines (33 loc) · 973 Bytes
/
ProductExceptSelf.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Problem-Link: https://leetcode.com/problems/product-of-array-except-self/
#include<vector>
using namespace std;
class ProductExceptSelf {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> product;
int overallProduct = 1;
int num_zeros = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != 0) {
overallProduct *= nums[i];
} else {
++num_zeros;
}
}
for (int i = 0; i < nums.size(); ++i) {
if (num_zeros > 1) {
product.push_back(0);
continue;
} else if (nums[i] == 0) {
product.push_back(overallProduct);
} else {
if (num_zeros >0) {
product.push_back(0);
} else {
product.push_back(overallProduct/nums[i]);
}
}
}
return product;
}
};