Product of Array Except Self
来源:互联网 发布:coreldrawx4软件下载 编辑:程序博客网 时间:2024/05/16 06:53
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:起初看到这个题目的时候,第一反应是用先记录所有元素的乘积,然后遍历每个元素,并用该元素去除这个乘积即可,
后来发现若是数组中包含元素0,该方法就会出问题,同时也不符合题意;
思路2:用双重循环去做乘法,但是也不满足题意;
思路3:最后看了一下下面提示的与该题类似的题(trap water),想到用二次遍历,第一次遍历得到当前元素左边元素的乘积,
第二次遍历得到元素右边元素乘积,同时,与上次遍历保存的值做乘法。
代码:
public class Solution { public int[] productExceptSelf(int[] nums) { int length = nums.length; int[] output = new int[length]; int left = 1, right = 1; for(int i = 0; i < length; i++) { output[i] = left; left *= nums[i]; } for(int i = length - 1; i >= 0; i--) { output[i] *= right; right *= nums[i]; } return output; }}
0 0
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- Angular.JS + Require.JS + angular-async-loader 来实现异步加载 angular 模块
- android AsyncTask介绍
- mysql向表中插入时间
- Caffe cuDNN max-pooling with in-place dropout
- C++的面向对象的Dijkstra写法
- Product of Array Except Self
- 关于java初学者的心理
- 53. PHP 伪静态(2)
- Turn the corner
- cocos2d-x设计模式发掘之一:单例模式
- 排序算法(二):希尔排序
- FMDB总结及其中的一些注意点
- ScrollView 获取滑动方向
- 算法策略的总结