【leetcod】Product of Array Except Self -C++
2015-09-09 17:29
507 查看
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.)
大意:给一个数组a,然后返回一个数组b,b数组中的数是对应的是a数组中除了自己以外剩下所有数的乘积。不能使用除法。
假设数组为:
a1,a2,a3,a4
可以创建两个有规律数组
1,a1,a1a2,,a1a2a3
a2a3a4,a3a4,a4,1
然后对应相乘就可以了。
还可以只创建一个数组 1,a1,a1a2,,a1a2a3,此时最后一项已经对了,只差前面的了,然后逆序遍历,用一个临时变量来存储要乘的数据。
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.)
大意:给一个数组a,然后返回一个数组b,b数组中的数是对应的是a数组中除了自己以外剩下所有数的乘积。不能使用除法。
假设数组为:
a1,a2,a3,a4
可以创建两个有规律数组
1,a1,a1a2,,a1a2a3
a2a3a4,a3a4,a4,1
然后对应相乘就可以了。
还可以只创建一个数组 1,a1,a1a2,,a1a2a3,此时最后一项已经对了,只差前面的了,然后逆序遍历,用一个临时变量来存储要乘的数据。
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { if(nums.size() <= 1) { vector<int> ivec(nums.begin(),nums.end()); return ivec; } vector<int> ivec(nums.size(),1); for(int i = 1;i < nums.size();++i) { ivec[i] = ivec[i-1] * nums[i-1]; } int numtmp = 1; for(int i = nums.size() - 1; i >= 0;--i) { ivec[i] = ivec[i] * numtmp; numtmp *= nums[i]; } return ivec; } };
相关文章推荐
- C语言篇——指针(一)
- 关于&的思考
- C++STL之函数对象及谓词
- c++ 成员变量初始化
- 在 C/C++ 语言中特定的宏,如 __FUNCTION__
- C++用法的学习心得
- C++——运算符重载(四)
- 为什么要选择C/C++
- 收集的一些c++知识点与题目一
- c++获取系统时间(引用别人的博文)
- Effective C++学习进阶版
- ID 比较练习 C语言 文件操作 位置指针
- C语言中long long的用法
- c++中vetctor的用法
- C++构造函数的继承问题
- C++用法的学习心得
- C++中的友元 friend
- 最大连续子数组和
- 列选主元Guass消元法求解方程组+c语言
- Floyd-Warshall 算法 C++实现