2021年02月11日 周四天气晴 【不悲叹过去,不荒废现在,不惧怕未来】
1. 问题简介
2. 题解
图源 Krahets ,侵删。
如上图,可以用两轮循环,第一轮计算左下角的乘积,第二轮计算右上角的乘积,再乘以左下角乘积,就得到了最终结果。
当然,也可以一轮计算解决问题,方法就是 左右开弓 ,同时计算左边和右边的乘积值,一轮循环解决问题。代码如下:
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
int n = a.size();
vector<int> res(n, 1);
// 左右开弓
int left = 1, right = 1;
for(int i = 0; i < n; i++){
res[i] *= left; // res[i]表示右边数乘积,在乘以左边数乘积left,即是结果
left *= a[i]; // 提前计算好下一个位置左边所有数的乘积
res[n-i-1] *= right; // res[n-i-1]表示左边数乘积,在乘以右边数乘积right,即是结果
right *= a[n-i-1]; // 提前计算好下一个位置右边所有数的乘积
}
return res;
}
};
参考文献
《剑指offer 第二版》
https://leetcode-cn.com/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/