Skip to content

Commit 222658e

Browse files
committed
product of array except self PR
1 parent f67b65a commit 222658e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
- URL : https://leetcode.com/problems/product-of-array-except-self/description/
2+
- points from constraints
3+
- 2 <= nums.length <= 10^5
4+
- if not use O(n) algorithm, a TLE occurs
5+
- -30 <= nums[i] <= 30
6+
- the production result can be negative
7+
- do not use an unsigned type for the result object.
8+
- The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.
9+
- There is no need to use a 64-bit (or larger) type for the result object.
10+
- However, it is not guaranteed that the intermediate object will always be a 32-bit type.
11+
12+
13+
14+
```cpp
15+
class Solution {
16+
public:
17+
vector<int> productExceptSelf(vector<int>& nums) {
18+
vector<int> idxOfZero;
19+
long long productRes = 1;
20+
for(int i=0;i<nums.size();i++){
21+
if(nums[i]==0){
22+
idxOfZero.push_back(i);
23+
}else{
24+
productRes *=nums[i];
25+
}
26+
}
27+
vector<int> res(nums.size(), 0);
28+
if(idxOfZero.size()>=2){
29+
return res;
30+
}else if(idxOfZero.size()==1){
31+
res[idxOfZero[0]] = productRes;
32+
return res;
33+
}
34+
35+
for(int i=0;i<nums.size();i++){
36+
res[i] = (int)(productRes / nums[i]);
37+
}
38+
return res;
39+
}
40+
};
41+
```
42+
43+
- O(n)
44+
- long long type for result object -> 64bit(by constraint #3)

0 commit comments

Comments
 (0)