【剑指offer-解题系列(52)】构建乘积数组
来源:互联网 发布:linux jdk1.7下载 编辑:程序博客网 时间:2024/05/21 22:24
题目描述
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
分析
采用两个数组 A[n] , B[n]分别记录除去第 i 个数后,
A数组记录从 1 ~ i-1 个数的乘积,
B数组记录从 i+1 ~ n 个数的乘积。
A数组记录从 1 ~ i-1 个数的乘积,
B数组记录从 i+1 ~ n 个数的乘积。
最后,只需要再次遍历数组,把AB数组相乘就可以得到最后结果
代码实现
vector<int> multiply(const vector<int>& A) {
int n = A.size();
vector<int>res;
if(n<=0)
return res;
int *a =new int[n];
int *b =new int[n];
memset(a,0,n*sizeof(int)); a[0] =1;
memset(b,0,n*sizeof(int)); b[n-1]=1;
///////////////////////////
for(int i=1;i<n;i++){
a[i]=a[i-1]*A[i-1];
}
for(int i=n-2;i>=0;i--){
b[i]=b[i+1]*A[i+1];
}
for(int i=0;i<n;i++){
res.push_back(a[i] *b[i]);
}
//////////////////////////
delete a;
delete b;
return res;
}
int n = A.size();
vector<int>res;
if(n<=0)
return res;
int *a =new int[n];
int *b =new int[n];
memset(a,0,n*sizeof(int)); a[0] =1;
memset(b,0,n*sizeof(int)); b[n-1]=1;
///////////////////////////
for(int i=1;i<n;i++){
a[i]=a[i-1]*A[i-1];
}
for(int i=n-2;i>=0;i--){
b[i]=b[i+1]*A[i+1];
}
for(int i=0;i<n;i++){
res.push_back(a[i] *b[i]);
}
//////////////////////////
delete a;
delete b;
return res;
}
阅读全文
0 0
- 【剑指offer-解题系列(52)】构建乘积数组
- 剑指Offer系列-面试题52:构建乘积数组
- 《剑指offer》:[52]构建乘积数组
- 剑指Offer 52 构建乘积数组
- 【剑指offer】题52:构建乘积数组
- 剑指offer 52 构建乘积数组
- 剑指offer(54):构建乘积数组
- 剑指offer(48)-构建乘积数组
- 剑指offer--构建乘积数组
- 《剑指offer》构建乘积数组
- 剑指offer-构建乘积数组
- 剑指offer:构建乘积数组
- 剑指offer:构建乘积数组
- 剑指offer:构建乘积数组
- [剑指offer]构建乘积数组
- 剑指offer|构建乘积数组
- 《剑指offer》-构建乘积数组
- 剑指offer 构建乘积数组
- EasyUI validType属性详解
- 447. Number of Boomerangs
- GVIM 菜单乱码和内容乱码
- 常用的代码压缩工具
- 598. Range Addition II的C++解法
- 【剑指offer-解题系列(52)】构建乘积数组
- InvalidDataAccessApiUsageException:Write operations are not allowed in read-only mode (FlushMode.NEV
- Excel VBA高效办公应用-第二章-Excel VBA编辑基础-Part1(VBA关键字)
- Spring源码之XML解析
- python数据迁移--未完
- Android7.0中文文档(API)-- ViewAnimator
- Codeforces 814C An impassioned circulation of affection【Dp】
- bzoj 4802: 欧拉函数 大整数分解
- QT学习 常见操作记录