Product of Array Except Self
2015-11-06 22:32
323 查看
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.)
思路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;
}
}
Given an array of n integers where n > 1,
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.)
思路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;
}
}
相关文章推荐
- U盘无法安装win10提示Your PC/Device needs to be repaired
- 正则表达式
- cocos2d-x设计模式发掘之三:管理者模式
- U盘无法安装win10提示Your PC/Device needs to be repaired
- 【Matlab开发】matlab中norm范数以及向量点积、绘图设置相关
- Spark到底解决了什么根本性的技术问题?
- JAVA中3大集合框架队列的使用
- cocos2d-x设计模式发掘之二:二段构建模式
- CentOS7安装JDK1.8
- Ubuntu下安装Intellij IDEA和PyCharm
- LightOJ - 1076 Get the Containers(二分)
- OnItemClickListener与OnScrollListener监听器
- 算法策略的总结
- 监督学习(机器学习)
- 树形dp题集之树的直径
- LightOJ - 1048 Conquering Keokradong(贪心)
- fastdfs环境搭建
- 14 Longest Common Prefix
- ScrollView 获取滑动方向
- CentOS 中安装和卸载 Emacs