Leetcode: Product of Array Except Self (60ms) analysis and solution
2015-09-17 23:13
387 查看
Problem:
Given an array of n integers where n > 1,
return an array
equal to
the product of all the elements of
Solve it without division and in O(n).
For example, given
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not
count as extra space for the purpose of space complexity analysis.)
Hide Tags
Array
Show Similar Problems
Analysis:
Using two round processing: forward and backward. See figure for detail:
//////////////////////////////////////////
//code 60ms
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> tmp(nums.size(), 1);
int n=nums.size();
//forward
for(int i=0;i<n-1;i++){
tmp[i+1]=tmp[i]*nums[i];
}
//backward
int m=1;
for (int j=n-1;j>-1;j--){
tmp[j]=m*tmp[j];
m=m*nums[j];
}
return tmp;
}
};
Given an array of n integers where n > 1,
nums,
return an array
outputsuch that
output[i]is
equal to
the product of all the elements of
numsexcept
nums[i].
Solve it without division and in O(n).
For example, given
[1,2,3,4], return
[24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not
count as extra space for the purpose of space complexity analysis.)
Hide Tags
Array
Show Similar Problems
Analysis:
Using two round processing: forward and backward. See figure for detail:
//////////////////////////////////////////
//code 60ms
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> tmp(nums.size(), 1);
int n=nums.size();
//forward
for(int i=0;i<n-1;i++){
tmp[i+1]=tmp[i]*nums[i];
}
//backward
int m=1;
for (int j=n-1;j>-1;j--){
tmp[j]=m*tmp[j];
m=m*nums[j];
}
return tmp;
}
};
相关文章推荐
- Linux2.6.32驱动笔记(3)分析应用程序read访问驱动过程
- druid.io sql支持
- [转]腾讯计费平台部分布式MySQL数据库TDSQL架构分析
- 2015第38周四杂记
- c++设计模式----Decorator(装饰)
- 只有0和1的数
- Opencv实现曼水填充算法-floodFill函数
- 漂亮简单的Android 自定义 Switch 控件!
- java 编程思想 阅读笔记(5)
- 封装malloc编写一个malloc16使得返回地址%16==0
- 读《设计心理学》一
- Kurento应用开发指南(以Kurento 6.0为模板) 之八: Kurento协议
- 将目标文件分为程序段与数据段两大类的原因
- jmeter中线程之间传递参数
- Linux bind-utils
- .net中动态对象的使用
- 对于开源菜谱的思考
- Mac中设置android adb环境变量
- hdu 1115 Lifting the Stone
- JSP的9大内置对象