product-of-array-except-self

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.)

Solution 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class {
public int[] productExceptSelf(int[] nums) {
int products = 1;
int zeroNum = 0;  //0的数目
int[] output = new int[nums.length]; 
for (int num : nums) {
products *= num;
if (num == 0)
zeroNum++; //统计0的数目
}
for (int i = 0; i < nums.length; i++) {
  //特殊情况,nums[i]=0
if (nums[i] == 0) {
  //除了本身之外还有0,所以except self之后为0
if (zeroNum > 1)
output[i] = 0;
//只有self为0,再遍历一遍
else {
output[i] = 1;
for (int j = 0; j < nums.length; j++)
if (j != i)
output[i] *= nums[j];
}
}
else output[i] = products / nums[i];
}
return output;
}
}

Solution 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size(), i = 0;
vector<int> output(n, 1);
int k = nums[n-1];
//计算self左边的乘积
for (i = 1; i < n; ++i)
output[i] = output[i-1] * nums[i-1];
// 计算self右边的乘积
for (i = n - 2; i >=0; --i)
{
output[i] *= k;
k *= nums[i];
}
return output;
}
};