[letecode java] Product of Array Except Self
来源:互联网 发布:java棕色rgb 编辑:程序博客网 时间:2024/06/04 04:52
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.)
利用一个left数组和right数组,left数组存储第i个数左边所有数的乘积,right存储第i个数右边所有数的乘积,则result[i]=left[i]*right[i]。时间花费为3n,满足o(n)要求,但空间复杂度却不满足要求。所以需要在数组更新上另想办法。而如果在一个数组上更新,result数组中应先存储right数组,用一个变量tmp存储当前的left值即可。代码如下:
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result =new int[nums.length];
result[nums.length-1]=1;
int temp=1;
for(int i=nums.length-2;i>=0;i--)
result[i]=result[i+1]*nums[i+1];
for(int i=0;i<nums.length;i++){
result[i]=temp*result[i];
temp=temp*nums[i];
}
return result;
}
}
- [letecode java] Product of Array Except Self
- (java) Product of Array Except Self
- 238. Product of Array Except Self(Java)
- 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
- hdu 2871 -Memory Control--线段树
- Subset I & II
- 卸载Source Insight 3时出现"Could not find the INSTALL.LOG"
- opencv画图函数
- 把word转换成pdf方法与应用
- [letecode java] Product of Array Except Self
- HDU 5009 Paint Pearls
- 遍历二叉树
- Android系统自带样式(android:theme)解析
- KMeans笔记 K值以及初始类簇中心点的选取
- Android-RoundCornerProgressBar——Android圆角进度条(Progress Bar)类库
- 快速打开Source的快捷键
- STL源码剖析 [简单应用总结二]
- Permutation sequence