238. Product of Array Except Self
来源:互联网 发布:网络借贷管理办法 编辑:程序博客网 时间:2024/06/11 18:08
题目
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.)
题意
不用除法, 在O(n)时间内, 求出数组每一个除了nums[i]以外其他所有数的乘积.
分析
将i位置上的乘积分成两部分:左边的[0: i-1]和右边的[i+1:n-1]
从左到右对每个i而言,左边部分乘积是可以累积上来的.
同理从右到左也是这样.
所以两轮循环, 先从左到右算出每个i左边所有数的乘积, 再从右到左算出每个i右边所有数的乘积
实现
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> res(nums.size()); res[0] = 1; for (int i = 1; i < nums.size(); i++) res[i] = res[i-1]*nums[i-1]; int rightCulmProdt = 1; for (int i = nums.size()-1; i >=0; i--) { res[i] *= rightCulmProdt; rightCulmProdt *= nums[i]; } 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
- python列表的基本知识
- URAL1947 Meander 思路
- 关于android中的两大布局LinearLayout、RelativeLayout
- Tensorflow 读取Txt和Csv格式数据
- 130. Surrounded Regions
- 238. Product of Array Except Self
- Windows物理磁盘扇区读写示例总结
- 数据结构12————二叉树的遍历和建立
- 序列有关BIF
- Hdoj 5702 Solving Order
- 为什么C++11引入了std::ref?
- Java知识点复习系列(5)
- 区块链技术的应用场景与常见疑问
- 740. Delete and Earn