CodeCollection2018
8/22/2019 - 1:06 PM

求数组中除了自己之外其他数的乘积,不用除法

public int[] productExceptSelf(int [] nums){
    int [] res = new int[nums.length];
    int [] left = new int [nums.length];
    left[0]=1;
    int[] right = new int[nums.length];
    right[nums.length-1] = 1;
    for(int i = 1; i < nums.length; i++){
        left[i] = left[i-1]*nums[i];
    }
    for(int i = nums.legnth-2; i >= 0; i--){
        right[i] = right[i+1]*nums[i];
    }
    for(int i  = 0; i < nums.length; i++){
        res [i] = left[i]*right[i];
    }
    return res;
}
public int productExceptSelf_WithConstantSpace(int [] nums){
    int [] res = new int [nums.length];
    int temp = 1;
    res[0] = 1;
    for(int i = 1 ; i < nums.length; i++){
        res[i] = res[i-1]*nums[i];
    }
    temp = nums[nums.length-1];
    for(int i = nums.length-2; i >= 0 ; i--){
        res[i] = res[i]*temp;
        temp *= nums[i];
    }
    return res;
}