0
Software Development

## 【Day 26】#238 - Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

``````Input:  [1,2,3,4]
Output: [24,12,8,6]
``````

Note: Please solve it without division and in O(n).

Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

## 解析

R陣列的最後一個元素為1，其餘每個元素皆為R陣列的後一個元素與nums陣列中相對位置的後一個元素之乘積，即`R[i] = R[i+1] * nums[i+1]`

## 解法

``````class Solution {
public int[] productExceptSelf(int[] nums) {

int length = nums.length;
int[] L = new int[length];
int[] R = new int[length];

L[0] = 1;
for (int i = 1; i < length; i++) {
L[i] = nums[i - 1] * L[i - 1];
}

R[length - 1] = 1;
for (int i = length - 2; i >= 0; i--) {
R[i] = nums[i + 1] * R[i + 1];
}

for (int i = 0; i < length; i++) {
}
}
}
``````

``````class Solution {
public int[] productExceptSelf(int[] nums) {

int length = nums.length;

for (int i = 1; i < length; i++) {
}

int R = 1;
for (int i = length - 1; i >= 0; i--) {
R *= nums[i];
}
}
}
``````

LeetCode刷題日記30