- LeetCode 238. Product of Array E
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
- 238. Product of Array Except Sel
LeetCode Link
下面的 Solution 可以 optimize to O(1) space:
- leftToRight as res
- rightToLeft store with a temp variable
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] leftToRight = new int[len + 1];
int[] rightToLeft = new int[len + 1];
leftToRight[0] = 1;
rightToLeft[len] = 1;
for (int i = 0; i < len; i++) {
leftToRight[i + 1] = leftToRight[i] * nums[i];
rightToLeft[len - i - 1] = rightToLeft[len - i] * nums[len - i - 1];
}
int[] res = new int[len];
for (int i = 0; i < len; i++) {
res[i] = leftToRight[i] * rightToLeft[i + 1];
}
return res;
}
网友评论