Product of Array Except Self
Total Accepted: 26470 Total Submissions: 66930 Difficulty: Medium
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.)
限定了不能用除法,和时间复杂度。
但Follow up我没太懂,是不允许申请额外的空间吗?
这次本来想用位运算中的异或运算写,但是发现那样有固有缺陷——对负数不起效果。而且越改越臃肿。
最后在Discuss中找到一个好方法, 这个方法申请了额外的数组。
优点:
- 得到数组中新的一个数字时,借助了上一位,从而不用再次遍历整个数组
- 方法很巧妙
下面是看完解答后自己写的:
Java语言写的
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
res[0] = 1;
for (int i = 1; i < nums.length; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = nums.length - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}
}