算出前后的乘积 最后再相加
1 class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 int size = nums.length; 4 int[] result = new int[size]; 5 int[] fwd = new int[size], bwd = new int[size]; 6 fwd[0] = 1; bwd[size - 1] = 1; 7 for(int i = 1; i < nums.length; i++) { 8 fwd[i] = fwd[i - 1] * nums[i - 1]; 9 }10 for(int j = size - 2; j >= 0; j--) {11 bwd[j] = bwd[j + 1] * nums[j + 1];12 }13 for(int k = 0; k < nums.length; k++) {14 result[k] = fwd[k] * bwd[k];15 }16 return result;17 }18 }
优化的方法是不用单独算出前后乘积,直接把前面的乘积放进result数组里,然后再用后面的乘积直接乘result的各个元素
100%:
1 class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 int size = nums.length; 4 int[] result = new int[size]; 5 result[0] = 1; int bwd = 1; 6 for(int i = 1; i < nums.length; i++) { 7 result[i] = result[i - 1] * nums[i - 1]; 8 } 9 for(int j = size - 1; j >= 0; j--) {10 result[j] = result[j] * bwd;11 bwd *= nums[j];12 13 }14 return result;15 }16 }