File tree Expand file tree Collapse file tree 1 file changed +11
-18
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +11
-18
lines changed Original file line number Diff line number Diff line change 11class Solution {
22 public:
33 vector<int > productExceptSelf (vector<int >& nums) {
4- int zero = 0 ;
5- int product = 1 ;
6- vector<int > result;
4+ int n = nums.size ();
5+ vector<int > result (n, 1 );
76
8- for ( int i = 0 ; i < nums. size (); i++){
9- if (nums[i] == 0 )
10- zero++;
11- else
12- product *= nums[i];
7+ int left = 1 ;
8+
9+ for ( int i = 0 ; i < n; i++){
10+ result[i] = left;
11+ left *= nums[i];
1312 }
1413
15- for (int i = 0 ; i < nums.size (); i++){
16- if (zero > 1 )
17- result.push_back (0 );
18- else if (zero == 1 ){
19- if (nums[i] == 0 )
20- result.push_back (product);
21- else
22- result.push_back (0 );
23- }else
24- result.push_back (product / nums[i]);
14+ int right = 1 ;
15+ for (int i = n - 1 ; i >= 0 ; i--){
16+ result[i] *= right;
17+ right *= nums[i];
2518 }
2619
2720 return result;
You can’t perform that action at this time.
0 commit comments