//剑指 Offer 66. 构建乘积数组
//维护两个数组:l,r
//l[i]:原数组左边所有元素的乘积
//r[i]:原数组右边所有元素的乘积
//这样,ans[i]就等于l[i] * r[i]
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
int n = a.size();
vector<int>l(n, 1);
vector<int>r(n, 1);
for (int i = 1; i < n; i++) {
l[i] = l[i - 1] * a[i - 1];
r[n - 1 - i] = r[n - i] * a[n - i];
}
auto ans = a;
for (int i = 0; i < n; i++)
ans[i] = l[i] * r[i];
return ans;
}
};
LeetCode剑指 Offer 66. 构建乘积数组
最新推荐文章于 2024-08-23 11:46:54 发布