File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time complexity: O(n)
2
+ // Spatial complexity: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ vector<int > productExceptSelf (vector<int >& nums) {
7
+ int numberOfZero = 0 , productNums = 1 ;
8
+
9
+ for (int num : nums) {
10
+ if (num == 0 ) {
11
+ ++numberOfZero;
12
+ continue ;
13
+ }
14
+
15
+ productNums *= num;
16
+ }
17
+
18
+ vector<int > answer (nums.size (), 0 );
19
+ if (numberOfZero > 1 ) {
20
+ return answer;
21
+ }
22
+
23
+ if (numberOfZero == 1 ) {
24
+ for (int i = 0 ; i < nums.size (); ++i) {
25
+ if (nums[i] == 0 ) {
26
+ answer[i] = productNums;
27
+ return answer;
28
+ }
29
+ }
30
+ }
31
+
32
+ for (int i = 0 ; i < nums.size (); ++i) {
33
+ if (nums[i] == 0 ) {
34
+ answer[i] = productNums;
35
+ continue ;
36
+ }
37
+
38
+ answer[i] = productNums / nums[i];
39
+ }
40
+
41
+ return answer;
42
+ }
43
+ };
You can’t perform that action at this time.
0 commit comments