File tree Expand file tree Collapse file tree 1 file changed +81
-1
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +81
-1
lines changed Original file line number Diff line number Diff line change 1
- // set-up
1
+ // Optimize complexity
2
+ class Solution {
3
+ public:
4
+ vector<int > productExceptSelf (vector<int >& nums) {
5
+
6
+ vector<int > answer (nums.size (), 1 );
7
+ // production before nums[i] from index 0
8
+ int before = 1 ;
9
+
10
+ for (int i=0 ; i<nums.size ()-1 ; i++)
11
+ {
12
+ before *= nums[i];
13
+ answer[i+1 ] *= before;
14
+ }
15
+
16
+ // nums[i] 기준 앞에서 production 해놓은 것에 nums[i] 기준 뒤에 것들을 production from index n-1
17
+ // production after nums[i] to answer[i-1]
18
+ // answer[i-1] * after
19
+ int after = 1 ;
20
+ for (int i=nums.size ()-1 ; i>0 ; i--)
21
+ {
22
+ after *= nums[i];
23
+ answer[i-1 ] *= after;
24
+ }
25
+
26
+ return answer;
27
+ }
28
+ };
29
+
30
+
31
+
32
+ // using division operation
33
+ /*
34
+ class Solution {
35
+ public:
36
+ vector<int> productExceptSelf(vector<int>& nums) {
37
+ int zeroCnt = 0;
38
+ int allProduct = 1;
39
+ vector<int> answer(nums.size());
40
+
41
+ for(int i=0; i<nums.size(); i++)
42
+ {
43
+ allProduct *= nums[i];
44
+ if(nums[i]==0)
45
+ {
46
+ zeroCnt++;
47
+ }
48
+ }
49
+
50
+ if(zeroCnt == 0)
51
+ {
52
+ for(int i=0; i<nums.size(); i++)
53
+ {
54
+ answer[i] = allProduct/nums[i];
55
+ }
56
+ }
57
+ else if(zeroCnt == 1)
58
+ {
59
+ int zeroIdx = 0;
60
+ int allProductWithoutZero = 1;
61
+
62
+ for(int i=0; i<nums.size(); i++)
63
+ {
64
+ if(nums[i]==0)
65
+ {
66
+ zeroIdx = i;
67
+ }
68
+ else
69
+ {
70
+ allProductWithoutZero *=nums[i];
71
+ answer[i] = 0;
72
+ }
73
+ }
74
+
75
+ answer[zeroIdx] = allProductWithoutZero;
76
+ }
77
+
78
+ return answer;
79
+ }
80
+ };
81
+ */
You can’t perform that action at this time.
0 commit comments