238. product of array except self

explanation

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

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

  1. go through the array from begin to end
  2. go through the array from end to begin

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class  {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}

int[] result = new int[nums.length];
result[0] = 1;
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
int temp = 1;
for (int i = nums.length - 1; i >= 0; i--) {
result[i] = result[i] * temp;
temp = temp * nums[i];
}
return result;

}
}