您的位置:首页 > 其它

LeetCode Product of Array Except Self 数组

2015-11-15 15:08 351 查看
思路:

不能用除法。

假设要算
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: