leetcode [#237]

目录

题目

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

Note
given [1,2,3,4], return [24,12,8,6].


解决方案

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
33
public class Solution {
public int[] productExceptSelf(int[] nums) {
int N = nums.length;
int[] output = new int[N];
int zero = 0;
int total = 1;
for(int i = 0; i < N; i++){
if(nums[i] == 0){
zero++;
} else {
total *= nums[i];
}
}
if(zero >= 2){
for(int i=0;i<N;i++){
output[i] = 0;
}
} else if(zero == 1){
for(int i=0;i<N;i++){
if(nums[i] == 0){
output[i] = total;
} else {
output[i] = 0;
}
}
} else {
for(int i = 0; i < N; i++){
output[i] = total / nums[i];
}
}
return output;
}
}

注意事项

  1. 考虑了0的个数进行单独处理。
  2. 上述方法使用了除法,不符合题目要求,discuss中vote较高的回答为:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public int[] productExceptSelf(int[] nums) {
    int[] result = new int[nums.length];
    for (int i = 0, tmp = 1; i < nums.length; i++) {
    result[i] = tmp;
    tmp *= nums[i];
    }
    for (int i = nums.length - 1, tmp = 1; i >= 0; i--) {
    result[i] *= tmp;
    tmp *= nums[i];
    }
    return result;
    }

该方法很巧妙,第一遍遍历算出了每个元素左边的值的乘积,保留该结果。再反向遍历,在刚才乘积结果的基础上再累成每个元素右边的值,最后就得到了答案。