[剑指Offer][数组]构建乘积数组
时间:2021-05-24 10:03:36
收藏:0
阅读:0
题目描述
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。(注意:规定B[0] = A[1] * A[2] * ... * A[n-1],B[n-1] = A[0] * A[1] * ... * A[n-2])
对于A长度为1的情况,B无意义,故而无法构建,因此该情况不会存在。
1 public class Solution { 2 public int[] multiply(int[] array) { 3 if(array.length <= 1) { 4 return new int[0]; 5 } 6 int[] result = new int[array.length]; 7 for(int i = 0; i < array.length; i ++) { 8 result[i] = 1; 9 for(int j = 0; j < array.length; j ++) { 10 if(j == i) { 11 continue; 12 } 13 result[i] = result[i] * array[j]; 14 if(result[i] == 0) { 15 break; 16 } 17 } 18 } 19 return result; 20 } 21 }
1 public class Solution { 2 public int[] multiply(int[] array) { 3 if(array.length <= 1) { 4 return new int[0]; 5 } 6 int[] result = new int[array.length]; 7 int[] left = new int[array.length]; 8 int[] right = new int[array.length]; 9 left[0] = 1; 10 right[array.length - 1] = 1; 11 for(int i = 1; i < array.length; i ++) { 12 left[i] = left[i - 1] * array[i - 1]; 13 } 14 for(int j = array.length - 2; j >= 0; j --) { 15 right[j] = right[j + 1] * array[j + 1]; 16 } 17 for(int m = 0; m < array.length; m ++) { 18 result[m] = left[m] * right[m]; 19 } 20 return result; 21 } 22 }
评论(0)