LeetCode Product of Array Except Self 数组
2015-11-15 15:08
351 查看
思路:
不能用除法。
假设要算
那么
所以可以两次遍历数组,第一次正向遍历,算每个数字左边的乘积,保存在
时间复杂度O(N),空间复杂度O(N)。
java code:
不能用除法。
假设要算
x[i]的
ouput[i]:
那么
x[i]左边所有的数字乘起来,再乘以
x[i]右面所有的数字乘起来的积就是答案。
所以可以两次遍历数组,第一次正向遍历,算每个数字左边的乘积,保存在
ouput[i]中,第二次反向遍历,算每个数字右面所有数字的乘积,再乘以上一次遍历的结果,就是每个位置最后的答案。
时间复杂度O(N),空间复杂度O(N)。
java code:
public class Solution { public int[] productExceptSelf(int[] nums) { int len = nums.length; int[] ans = new int[len]; ans[0] = 1; for(int i = 1; i < len; ++i) { ans[i] = nums[i - 1] * ans[i - 1]; } int right = 1; for(int i = len - 1; i >= 0; --i) { ans[i] = ans[i] * right; right = nums[i] * right; } return ans; } }
相关文章推荐
- Windows7 64bit VS2013 Caffe train MNIST操作步骤
- Windows7 64bit VS2013 Caffe train MNIST操作步骤
- vc中内存对齐
- 汇编里寄存器的作用
- ERROR 001362:Failed to extract manifest from uploaded service definition.无法从上传的服务定义中提取清单。
- 安装win10体验
- Windows上Python3.5安装Scrapy(lxml)
- 安装win10体验
- c语言 基本I/O 操作
- CodeTyphon32中自带例子源码:画出漂亮的线、箭头、形状
- c语言有趣的位运算
- Android中Service的基本理解和使用
- 音乐外链转换工具
- shell入门-特殊符号
- UI之textField文本框
- static在c语言中的作用
- 个人博客作业week7
- c 设置 控制台 颜色
- 几本对于笔试和面试有用的书
- CSS+DIV之1-10