238. Product of Array Except Self (后两种方法有待进一步研究)
来源:互联网 发布:广州行知职高 编辑:程序博客网 时间:2024/05/16 19:13
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
方法一、
vector<int> productExceptSelf(vector<int>& nums) { int len = nums.size(); vector<int> left,right(len),ret(len); left.push_back(1); for(int i=1; i<len; i++){ left.push_back(left[i-1]*nums[i-1]); } right[len-1]=1; for(int i=len-2; i>=0; i--){ right[i]=right[i+1]*nums[i+1]; } for(int i=0; i<len; i++){ ret[i]=left[i]*right[i]; } return ret; }
方法二、O(n) time and O(n) space solution.
vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); vector<int> fromBegin(n); fromBegin[0]=1; vector<int> fromLast(n); fromLast[0]=1; for(int i=1;i<n;i++){ fromBegin[i]=fromBegin[i-1]*nums[i-1]; fromLast[i]=fromLast[i-1]*nums[n-i]; } vector<int> res(n); for(int i=0;i<n;i++){ res[i]=fromBegin[i]*fromLast[n-1-i]; } return res; }
方法三、
vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); int fromBegin=1; int fromLast=1; vector<int> res(n,1); for(int i=0;i<n;i++){ res[i]*=fromBegin; fromBegin*=nums[i]; res[n-1-i]*=fromLast; fromLast*=nums[n-1-i]; } return res; }
0 0
- 238. Product of Array Except Self (后两种方法有待进一步研究)
- [leetcode] 238.Product of Array Except Self
- [LeetCode]238.Product of Array Except Self
- [leetcode] 238. Product of Array Except Self
- Leetcode 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self LeetCode
- LeetCode 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- [LeetCode]238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- 238. Product of Array Except Self
- LeetCode *** 238. Product of Array Except Self
- ionic应用图标不能正常显示解决办法
- GitLab: No such project
- 利用Java反射实现JavaBean对象相同属性复制并初始化目标对象为空的属性的BeanUtils
- 性能优化-基于sqlite的优化
- 自定义导航返回按钮是用customView不可以的原因?
- 238. Product of Array Except Self (后两种方法有待进一步研究)
- poj1741 Tree
- PHP面向对象——构造函数、析构函数
- 触摸事件的分发与处理
- ML 工程师需了解的 10 大算法
- Git修改已经提交的注释
- 打印错误的堆栈信息
- 更为详细的Txtsetup.sif文件解释
- Dreamoon and Sums CodeForces - 476C