238. Product of Array Except Self
来源:互联网 发布:java svn资源库导出去 编辑:程序博客网 时间:2024/05/20 22:39
题面:
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]
.
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.)
题解:由于不能用除法,自然会想到当遍历到某一个数时,将其左边依次相乘,在将其右边依次相乘,即可。所以用两个数组记录。
代码:
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); vector<int> a(n); vector<int> b(n); a[0]=1; b[0]=1; vector<int> res(n); for(int i=1;i<n;i++){ a[i]=a[i-1]*nums[i-1]; b[i]=b[i-1]*nums[n-i]; } for(int i=0;i<n;i++){ res[i]=a[i]*b[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
- 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
- LeetCode 238. Product of Array Except Self
- oracle DBaaS 数据库云服务实践之一概要文件创建错误(Host credential should not be a root user)
- XML教程进阶06_总结
- 关于idea中无法正确依赖本地仓库,且无法连接远程仓库的解决办法
- Ajax
- 练习67
- 238. Product of Array Except Self
- MVC,MVP 和 MVVM的图示区别
- [svc]elk5.x x-pack插件使用(elasticsearch5)
- maven创建Web项目启动错误The servlets named [X] and [Y] are both mapped to the url-pattern [/DemoServlet]
- springmvc环境搭建以及常见问题解决
- ASP.NET WebAPI 连接数据库
- 重绘与回流
- 练习68
- VS2012破解版VisualAssist