【leetcode】Product of Array Except Self
来源:互联网 发布:威风堂堂mmd镜头数据 编辑:程序博客网 时间:2024/06/05 23: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.)
Subscribe to see which companies asked this question
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> result; int tmp = 1; result.push_back(tmp); for (vector<int>::const_iterator it = nums.begin(); it != nums.end() - 1; ++it) { tmp *= (*it); result.push_back(tmp); } tmp = 1; vector<int>::iterator it_result = result.end() - 2; for (vector<int>::const_iterator it = nums.end() - 1; it != nums.begin(); --it) { tmp *= (*it); (*it_result) *= tmp; --it_result; } return result; }};
Personal Note:
遍历nums两次,第一次正序,计算索引i之前各数乘积并存入result,第二次反序,计算索引i之后各数乘积并与之前result相乘,得到最终result。
0 0
- [leetcode][array] Product of Array Except Self
- 【LeetCode】237 Product of Array Except Self
- #leetcode#Product of Array Except Self
- leetcode 238: Product of Array Except Self
- [leetcode] 238.Product of Array Except Self
- [leetcode] Product of Array Except Self
- LeetCode Product of Array Except Self
- leetCode(43):Product of Array Except Self
- LeetCode Product of Array Except Self
- 【leetcode】Product of Array Except Self
- 【leetcode】Product of Array Except Self
- leetcode: Product of Array Except Self
- [leetcode] Product of Array Except Self
- [LeetCode] Product of Array Except Self
- Leetcode: Product of Array Except Self
- LeetCode 238: Product of Array Except Self
- LeetCode-Product of Array Except Self
- Leetcode #238 Product of Array Except Self
- java问题1解决方法:repaint()(更新ing)
- java类、抽象类和接口
- NOIP一道水题
- leetcode137 Single Number II
- 经济学原理-曼昆 学习笔记一
- 【leetcode】Product of Array Except Self
- Android整合SlidingMenu和Actionbarsherlock解决Actionbar的冲突
- fork()函数
- Button.titleLabel.text.length与Button.currentTitle.lenth的区别?
- linux 的一些关于操作目录的命令
- iOS 动态移除tableView某行cell
- segmentation fault, 段错误简单定位步骤
- java中获取用户的输出信息
- Add Binary