Product of Array Except Self
2015-09-09 16:03
267 查看
Product of Array Except Self Tota
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.)
Hide Tags Array
Hide Similar Problems (H) Trapping Rain Water (M) Maximum Product Subarray (H) Paint House II
**因为题目要求时间复杂度为O(n^2)且不能用除法,所以不能用先算出sum,再除以num[i]的方法(除数为0,运算不不合法)。
观察图,可知该题目可以用数i左边的数积*数i右边的数积。且可以看做l[0]=1,r[n-1]=1。
最后可知,results[i]=left[i]*right[i].
此算法的复杂度为O(n)**
代码:
可参考:http://blog.csdn.net/yangliuy/article/details/46954779
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.)
Hide Tags Array
Hide Similar Problems (H) Trapping Rain Water (M) Maximum Product Subarray (H) Paint House II
**因为题目要求时间复杂度为O(n^2)且不能用除法,所以不能用先算出sum,再除以num[i]的方法(除数为0,运算不不合法)。
观察图,可知该题目可以用数i左边的数积*数i右边的数积。且可以看做l[0]=1,r[n-1]=1。
最后可知,results[i]=left[i]*right[i].
此算法的复杂度为O(n)**
代码:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int i; int len=nums.size(); vector<int> results,left,right; if(len < 2) return results; left[0]=1; right[len-1]=1; //左边 for(i=0;i<len;i++){ left[i+1]=left[i]*nums[i]; } //右边 for(i=len-1;i>=1;i--){ right[i-1]=right[i]*nums[i]; } for(i=0;i<len;i++){ results[i]=left[i]*right[i]; } return results; } };
可参考:http://blog.csdn.net/yangliuy/article/details/46954779
相关文章推荐
- 阿里云服务器配置记录
- MD5加密与BASE64编码
- 嵌入式程序员面试题
- 最新 IntelliJ Idea 14 安装 Golang 插件 google-go-lang-idea-plugin 的方法
- bitnami redmine 安装插件
- Kth Smallest Number in Sorted Matrix
- SBT与Play配置文件
- Android应用框架-Volley网络通信框架
- mse
- Android sqlite执行insert,英文单引号报错问题的解决
- crontab 调用shell 脚本不运行
- Android之AutoCompleteTextView自动匹配(笔记)
- Linux 文件系统(二)---执行过程及结构间的关系
- 快递100 官方api技术文档 错误 更新 快递公司网络异常 解决方法
- Sharepoint Ribbon Loaction
- typedef NS_OPTIONS 位移的枚举
- 地理坐标计算
- hdu 1402 A * B Problem Plus FFT模板
- Effective Objective-C 2.0 第6条:理解“属性”
- 访问asp网站时,页面上显示请求的资源在使用中