当前位置:网站首页>【剑指 Offer】66. 构建乘积数组
【剑指 Offer】66. 构建乘积数组
2022-07-05 16:22:00 【LuZhouShiLi】
剑指 Offer 66. 构建乘积数组
题目
给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能使用除法。
思路
https://leetcode.cn/problems/gou-jian-cheng-ji-shu-zu-lcof/solution/mian-shi-ti-66-gou-jian-cheng-ji-shu-zu-biao-ge-fe/
- 初始化一个数组和原数组一样,b[0] = 1,声明一个辅助变量tmp = 1
- 计算b[i]的下三角各个元素的乘积,直接乘入b[i]
- 计算b[i]的上三角各元素的乘积,记为tmp,并乘入b[i]
- 返回b
代码
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
int length = a.size();
if(length == 0)
{
return {
};
}
vector<int> b(length,1); // 声明一个长度为length的向量 初始值都是1
b[0] = 1;
int tmp = 1;
// 自上而下计算下三角矩阵
//
for(int i = 1; i < length; i++)
{
b[i] = b[i - 1] * a[i - 1];
}
for(int i = length -2; i >= 0; i--)
{
tmp *= a[i + 1];// 必须声明一个临时变量进行存储 不可以是 b[i] *= a[i+1]
b[i] *= tmp;
}
return b;
}
};
边栏推荐
- Single merchant v4.4 has the same original intention and strength!
- 普洛斯数据中心发布DC Brain系统,科技赋能智慧化运营管理
- [deep learning] [original] let yolov6-0.1.0 support the txt reading dataset mode of yolov5
- [729. My schedule I]
- Writing method of twig array merging
- [729. My Schedule i]
- Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
- Jarvis OJ Webshell分析
- 【729. 我的日程安排錶 I】
- 阈值同态加密在隐私计算中的应用:解读
猜你喜欢
Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
采用药丸屏的iPhone14或引发中国消费者的热烈抢购
The new version of effect editor is online! 3D rendering, labeling, and animation, this time an editor is enough
Starkware: to build ZK "universe"
Single merchant v4.4 has the same original intention and strength!
Basic introduction to the control of the row component displaying its children in the horizontal array (tutorial includes source code)
npm安装
解决CMakeList find_package找不到Qt5,找不到ECM
Jarvis OJ Webshell分析
If you can't afford a real cat, you can use code to suck cats -unity particles to draw cats
随机推荐
树莓派4b安装Pytorch1.11
Today's sleep quality record 79 points
解决CMakeList find_package找不到Qt5,找不到ECM
Google Earth Engine(GEE)——Kernel核函数简单介绍以及灰度共生矩阵
Google Earth engine (GEE) -- a brief introduction to kernel kernel functions and gray level co-occurrence matrix
有序链表集合求交集 方法 总结
【 brosser le titre 】 chemise culturelle de l'usine d'oies
阈值同态加密在隐私计算中的应用:解读
DenseNet
Learnopongl notes (I)
It is forbidden to copy content JS code on the website page
Jarvis OJ Flag
Data access - entityframework integration
[es6] 模板字符串内添加if判断或添加三元运算符判断
[729. My schedule I]
[61dctf]fm
二叉树相关OJ题
SQL injection of cisp-pte (Application of secondary injection)
OneForAll安装使用
如何将mysql卸载干净