LeetCode-Product of Array Except Self
2015-07-31 10:18
190 查看
Given an array of n integers where n > 1,
return an array
equal to the product of all the elements of
Solve it without division and in O(n).
For example, given
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.)
自己没倒腾出来,确实挺难想的,但是当得知其中的奥秘时,不时感觉此算法真是妙。
题目大致意思就是求一个output数组,output[i]为数组nums数组除nums[i]之外数字的所有乘积,比如:
要求不用除法,时间复杂度O(n)
解题思路基于以下集合
很显然,这两个集合都可以在O(n)的时间复杂度求得,之后两个集合对应位置相乘即为所得。是不是很妙?
空间复杂度为O(n)的实现:
nums,
return an array
outputsuch that
output[i]is
equal to the product of all the elements of
numsexcept
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.)
自己没倒腾出来,确实挺难想的,但是当得知其中的奥秘时,不时感觉此算法真是妙。
题目大致意思就是求一个output数组,output[i]为数组nums数组除nums[i]之外数字的所有乘积,比如:
Input : [1, 2, 3, 4, 5] Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24]
要求不用除法,时间复杂度O(n)
解题思路基于以下集合
{ 1, a[0], a[0]*a[1], a[0]*a[1]*a[2], } { a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, }
很显然,这两个集合都可以在O(n)的时间复杂度求得,之后两个集合对应位置相乘即为所得。是不是很妙?
空间复杂度为O(n)的实现:
public int[] productExceptSelf(int[] nums) { int[] productBelow = new int[nums.length]; int n = 1; for (int i = 0; i < nums.length; i++) { productBelow[i] = n; n *= nums[i]; } int[] productAbove = new int[nums.length]; n = 1; for (int i = nums.length-1; i >= 0; i--) { productAbove[i] = n; n *= nums[i]; } int[] output = new int[nums.length]; for (int i = 0; i < nums.length; i++) { output[i] = productAbove[i] * productBelow[i]; } return output; }但是,如果要求是O(1)的空间复杂度呢?只需要把最后两步合二为一即可:
int[] output = new int[nums.length]; int n = 1; for (int i = 0; i < nums.length; i++) { output[i] = n; n *= nums[i]; } n = 1; for (int i = nums.length-1; i >= 0; i--) { output[i] *= n; n *= nums[i]; } return output;
相关文章推荐
- jquery全局变量---同步请求设置
- 对__doPostback函数的理解和应用
- 并查集详解
- b72d003ef478442aa3f5acc02324a8fd
- 数据结构学习--树(一)
- 你了解SVN, CVS等版本控制器吗?
- win10来了,linux你准备好了吗?
- Android获取手机配置信息
- c++11之unique_ptr
- 天仙配
- checkStyle
- nRF51822 白名单
- Spring框架概述
- LVS Nginx HAProxy 的比较
- 访问者设计模式
- Atom飞行手册翻译: 2.4 编辑和删除文本
- Spring MVC 中的 forward 和 redirect
- 毕业季,你在哪里?你在做什么?你开心吗?
- word文档转换成pdf格式在线转换
- 面试宝典第三版第八章8.2正确程序