LeetCode Product of Array Except Self

过早优化是万恶之源= =

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int l = nums.length;
        int[] output = new int[l];
        int[] a = new int[l];
        int[] b = new int[l];
        for(int i=0; i<l; i++){
            a[i] = 1;
            b[i] = 1;
        }
        for(int i=1; i<l; i++){
            int j = l-i-1;
            a[i] *= nums[i-1] * a[i-1];
            b[j] *= nums[j+1] * b[j+1];
        }
        for(int i=0; i<l; i++) output[i] = a[i] * b[i];
        return output;
    }
}

 

优化:用一个变量代替数组

public class Solution {
public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] res = new int[n];
    res[0] = 1;
    for (int i = 1; i < n; i++) {
        res[i] = res[i - 1] * nums[i - 1];
    }
    int right = 1;
    for (int i = n - 1; i >= 0; i--) {
        res[i] *= right;
        right *= nums[i];
    }
    return res;
}