当前位置:网站首页>【剑指 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;
}
};
边栏推荐
猜你喜欢
中国广电正式推出5G服务,中国移动赶紧推出免费服务挽留用户
怎样在电脑上设置路由器的WiFi密码
深潜Kotlin协程(二十一):Flow 生命周期函数
DeSci:去中心化科学是Web3.0的新趋势?
HiEngine:可媲美本地的云原生内存数据库引擎
2020-2022两周年创作纪念日
文件操作--I/O
If you can't afford a real cat, you can use code to suck cats -unity particles to draw cats
Detailed explanation of use scenarios and functions of polar coordinate sector diagram
【深度学习】深度学习如何影响运筹学?
随机推荐
StarkWare:欲构建ZK“宇宙”
Google Earth engine (GEE) -- a brief introduction to kernel kernel functions and gray level co-occurrence matrix
How can programmers improve their situation?
网站页面禁止复制内容 JS代码
HiEngine:可媲美本地的云原生内存数据库引擎
树莓派4b安装Pytorch1.11
帮忙看看是什么问题可以吗?[ERROR] Could not execute SQL stateme
如何安装mysql
[brush questions] effective Sudoku
How does win11 change icons for applications? Win11 method of changing icons for applications
Android 隐私沙盒开发者预览版 3: 隐私安全和个性化体验全都要
Detailed explanation of use scenarios and functions of polar coordinate sector diagram
Games101 notes (III)
【机器人坐标系第一讲】
BS-XX-042 基于SSM实现人事管理系统
Jarvis OJ simple network management protocol
Games101 notes (I)
Summary of methods for finding intersection of ordered linked list sets
国产芯片产业链两条路齐头并进,ASML真慌了而大举加大合作力度
[es6] 模板字符串内添加if判断或添加三元运算符判断