zl程序教程

您现在的位置是:首页 >  后端

当前栏目

剑指 Offer 66. 构建乘积数组

数组 构建 Offer 乘积 66
2023-09-11 14:19:00 时间

 

思路

 

方法:对称遍历

 

 1 class Solution {
 2 public:
 3     vector<int> constructArr(vector<int>& a) {
 4         if(a.empty())
 5             return vector<int>();
 6             
 7         vector<int> b(a.size());
 8         b[0] = 1;
 9 
10         for(int i = 1; i < b.size(); ++i) {
11             b[i] = b[i-1] * a[i-1];
12         } 
13 
14         int tmp = 1;
15         for(int i = b.size()-2; i >= 0; --i) {
16             tmp *= a[i+1];
17             b[i] *= tmp;
18         }
19 
20         return b;
21     }
22 };

 

参考

面试题66. 构建乘积数组(表格分区,清晰图解)