LeetCode(238)Product of Array Except Self
来源:互联网 发布:游戏优化 编辑:程序博客网 时间:2024/04/29 19:08
一开始最直接的思路当然是:对于0号位置元素,将剩下的元素依次累乘,然后保存;对于1号位置,重复上述动作。
可是题目的意思是我们只能在o(n)时间内完成,上述算法的时间的复杂度是o(n^2),下面在已有方案上优化,优化的方法是找出冗余计算,我们发现:以0号位置和1号位置为例,如果我们已经知道0号位置对应的乘积为p,那么1号位置对应的乘积为p/nums[1]*nums[0],即0号位置和1号位置对应的乘积是有联系的,0号位置的乘积可以-》推出1号位置,同样1号位置可以推出2号位置等等
至此,算法已经是可行的。
后来实际编码时,我发现为何不一开始将所有项相乘,然后再除以对应位置呢,终于找到最佳算法。
c++代码如下
class Solution {public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> result(nums.size(), 0); long long sum = 1; //deal with circumtance in which has 0 element for(int i = 0; i < nums.size(); i++) { if(nums[i] == 0) { for(int j = 0; j < i; j++) sum *= nums[j]; for(int j = i + 1; j < nums.size(); j++) sum *= nums[j]; result[i] = sum; return result; } } for(int i = 0; i < nums.size(); i++) sum *= nums[i]; for(int i = 0; i < nums.size(); i++) result[i] = sum / nums[i]; return result; }};
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
- BASE.CSS一份css初始化代码
- 没有为 COM 互操作注册程序集 请使用 regasm.exe /tlb 注册该程序集——解决办法
- mysql主从复制讲解
- 我的第一偏博客 怎么写啊 是这样吗???
- 一个Linux中用于监控的简易shell脚本
- LeetCode(238)Product of Array Except Self
- 字符集和字符编码(Charset & Encoding)
- Shell 脚本面试问题大全
- 野人学Android基础篇之初探UI控件第五课--RadioGroup
- 开篇blog
- JavaScript基础2——变量、作用域和内存
- 关于ajax中URL传递中文产生乱码的问题
- HTTP文件传输
- ios开发-电话本的设计与实现