-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path238.cpp
More file actions
executable file
·91 lines (79 loc) · 1.93 KB
/
Copy path238.cpp
File metadata and controls
executable file
·91 lines (79 loc) · 1.93 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <cstddef>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
int tick = 1;
int zeroCount = 0;
for (auto& num : nums) {
if (num != 0)
tick *= num;
else
zeroCount++;
}
if (zeroCount > 1) {
return vector<int>(n, 0);
}
vector<int> answer(n);
for (size_t i = 0; i<n; i++) {
if (zeroCount > 0) {
answer[i] = (nums[i] == 0) ? tick : 0;
}
else {
answer[i] = tick / nums[i];
}
}
return answer;
}
};
/* Prefix & Suffix
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> res(n);
vector<int> pref(n);
vector<int> suff(n);
pref[0] = 1;
suff[n - 1] = 1;
for (int i = 1; i < n; i++) {
pref[i] = nums[i - 1] * pref[i - 1];
}
for (int i = n - 2; i >= 0; i--) {
suff[i] = nums[i + 1] * suff[i + 1];
}
for (int i = 0; i < n; i++) {
res[i] = pref[i] * suff[i];
}
return res;
}
};
Time & Space Complexity
Time complexity: O(n)
Space complexity: O(n)
*/
/* Prefix & Suffix (Optimal)
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, 1);
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int postfix = 1;
for (int i = n - 1; i >= 0; i--) {
res[i] *= postfix;
postfix *= nums[i];
}
return res;
}
};
Time & Space Complexity
Time complexity: O(n)
Space complexity:
O(1) extra space.
O(n) space for the output array.
*/