leetcode 238: Product of Array Except Self
来源:互联网 发布:网络共享文件夹打不开 编辑:程序博客网 时间:2024/06/10 01:04
Learn the idea from https://leetcode.com/discuss/49667/o-n-time-and-o-1-space-c-solution-with-explanation.
O(n) time and O(n) space method:
Take [1,2,3,4] as an example, fromBegin will be [1,1*1,1*1*2,1*1*2*3], and fromEnd will be [1,1*4,1*4*3,1*4*3*2]. So the result can be derived from multiplying numbers from the two vectors.
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); vector<int> res(n,1); vector<int> fromBegin(n,1); vector<int> fromEnd(n,1); for(int i=1;i<n;i++) { fromBegin[i]=fromBegin[i-1]*nums[i-1]; fromEnd[i]=fromEnd[i-1]*nums[n-i]; } for(int i=0;i<n;i++) res[i]*=fromBegin[i]*fromEnd[n-i-1]; return res; }};
Here, I can reduce the space complexity by using only two variables.
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); vector<int> res(n,1); int fromBegin=1; int fromEnd=1; for(int i=0;i<n;i++) { res[i]*=fromBegin; fromBegin*=nums[i]; res[n-i-1]*=fromEnd; fromEnd*=nums[n-i-1]; } return res; }};
0 0
- 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
- 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
- Product of Array Except Self - LeetCode 238
- 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
- [LeetCode 238] Product of Array Except Self
- LeetCode[238]Product of Array Except Self
- LeetCode之Best Time to Buy and Sell Stock II
- sql实现从两个表获取字段组成表数据再插入到函数表中
- x5studio的常用操作
- Git简单介绍(一)
- 科研日报 20150831 FFT ETHERNET
- leetcode 238: Product of Array Except Self
- 【JS】测试:HTML页面引入另一个HTML页面,同名ID会冲突吗
- poj 1442.Black Box
- iOS --- 使用GPUImage实现的简单滤镜效果
- 哲学家吃饭问题 代码实现如何 避免线程死锁
- 惠普一周
- 数据库设计(3)-基本ER模型构建
- NSURLSession-task三个子类
- (*(void (*)( ) )0)( )