当前位置:网站首页>[Jianzhi offer] 66 Build product array
[Jianzhi offer] 66 Build product array
2022-07-05 16:58:00 【LuZhouShiLi】
The finger of the sword Offer 66. Building a product array
subject
Given an array A[0,1,…,n-1], Please build an array B[0,1,…,n-1], among B[i] Is the value of an array A In addition to subscript i The product of other elements , namely B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]. Division cannot be used .
Ideas
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/
- Initializing an array is the same as the original array ,b[0] = 1, Declare an auxiliary variable tmp = 1
- Calculation b[i] The product of the elements of the lower triangle of , Multiply directly into b[i]
- Calculation b[i] The product of the elements of the upper triangle of , Write it down as tmp, And multiply in b[i]
- return b
Code
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
int length = a.size();
if(length == 0)
{
return {
};
}
vector<int> b(length,1); // Declare a length of length Vector The initial value is zero 1
b[0] = 1;
int tmp = 1;
// Calculate the lower triangular matrix from top to bottom
//
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];// You must declare a temporary variable to store Can not be b[i] *= a[i+1]
b[i] *= tmp;
}
return b;
}
};
边栏推荐
猜你喜欢
Games101 notes (II)
【729. 我的日程安排表 I】
【组队 PK 赛】本周任务已开启 | 答题挑战,夯实商品详情知识
用键盘输入一条命令
Spring Festival Limited "forget trouble in the year of the ox" gift bag waiting for you to pick it up~
How to set the WiFi password of the router on the computer
【刷题篇】有效的数独
Jarvis OJ Flag
Win11如何给应用换图标?Win11给应用换图标的方法
數據訪問 - EntityFramework集成
随机推荐
Is it safe to open a securities account by mobile phone? Detailed steps of how to buy stocks
【剑指 Offer】66. 构建乘积数组
How does the outer disk futures platform distinguish formal security?
How to uninstall MySQL cleanly
How was the middle table destroyed?
Jarvis OJ webshell analysis
Data access - entityframework integration
Jarvis OJ Flag
【剑指 Offer】61. 扑克牌中的顺子
PHP strict mode
Jarvis OJ Telnet Protocol
npm安装
采用药丸屏的iPhone14或引发中国消费者的热烈抢购
How can C TCP set heartbeat packets to be elegant?
文件操作--I/O
ECU introduction
Win11 prompt: what if the software cannot be downloaded safely? Win11 cannot download software safely
Domestic API management artifact used by the company
BS-XX-042 基于SSM实现人事管理系统
Jarvis OJ shell traffic analysis