238. Product of Array Except Self
2016-07-16 12:27
344 查看
题目:Product of Array Except Self
原题链接:https://leetcode.com/problems/product-of-array-except-self/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.)
给出一个整数数组(长度大于1),返回一个数组,其中对应每个位置上的元素值为原先数组中不含当前位置元素的其他所有元素的乘积,要求不能用除法,并且线性时间复杂度,并尽量只占用常数个空间用来计算。
例:给出数组 [1,2,3,4], 返回结果应该是 [24,12,8,6].
个人做法可以线性时间复杂度,但是只能达到线性空间复杂度,后面参考网上发现可以优化成常数空间复杂度。
假设初始数组是nums [ ],开两个数组front [ ] 和back [ ], 其中front [ i ] 存放从nums [ 1 ]到 nums [ i - 1 ]的乘积(front [ 1 ]设为1),back [ i ] 存放从nums [ i + 1 ] 到nums [ len - 1 ]的乘积(back [ len - 1 ]设为1 ),这样结果的每一位只要用front [ i ] * back [ i ] 就行了,代码如下:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int len = nums.size(); int front[len], back[len]; vector<int> ans; for(int i = 0; i < len; ++i){ if(i == 0){ front[i] = 1; back[len - 1 - i] = 1; }else{ front[i] = front[i - 1] * nums[i - 1]; back[len - 1 - i] = back[len - i] * nums[len - i]; } } for(int i = 0; i < len; ++i){ ans.push_back(front[i] * back[i]); } return ans; } };
由于开了2个数组,所以目前是线性空间复杂度,优化成O(1)复杂度也很简单,把 front 和 back 从数组换成 int ,然后每次把值直接乘到这两个整型上,然后立刻乘给ans数组就行。代码如下:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int len = nums.size(); int front = 1, back = 1; vector<int> ans(len,1); for(int i = 1; i < len; ++i){ front *= nums[i - 1]; ans[i] *= front; back *= nums[len - i]; ans[len - i -1] *= back; } return ans; } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解