题目要求
解法一:
非常普通的暴力解法,头铁硬算出每个乘积,然后存入数组,毫无新意。
Time: O(n^2) Space: O(n)
代码:
import java.util.*;
class Program {
public int[] arrayOfProducts(int[] array) {
// Write your code here.
if (array == null || array.length < 2) return array;
int[] res = new int[array.length];
for (int i = 0; i < array.length; i++) {
int temp = i;
int product = 1;
for (int j = 0; j < array.length; j++) {
if (i == j) continue;
product *= array[j];
}
res[i] = product;
}
return res;
}
}
解法二:
创建两个数组,第一个数组存从前到后的累乘结果,第二个数组存从后到前的累乘结果。结果数组将两个数组的结果结合。
Time: O(n) Space: O(1)
代码:
import java.util.*;
class Program {
public int[] arrayOfProducts(int[] array) {
// Write your code here.
if (array.length == 0 || array == null) return new int[] {};
int[] temp1 = new int[array.length];
temp1[0] = array[0];
for (int i = 1; i < array.length; i++) {
temp1[i] = array[i] * temp1[i - 1];
}
int[] temp2 = new int[array.length];
temp2[array.length - 1] = array[array.length - 1];
int j = array.length - 2;
for (int i = array.length - 2; i > 0; i--) {
temp2[i] = temp2[i + 1] * array[j];
j--;
}
int[] res = new int[array.length];
res[0] = temp2[1];
res[array.length - 1] = temp1[array.length - 2];
for (int i = 1; i < array.length - 1; i++) {
res[i] = temp1[i - 1] * temp2[i + 1];
}
return res;
}
}
解法三:
思路和第二种解法一样,只是做了一些优化。我们发现得出的的结果并不需要数组全部乘积作为计算参数,因此我们直接将其设置成1,然后用一个临时变量来存上一个数的累乘结果。然后继续计算两数组的数值,最后直接进行计算。
对于本题sample,我们的两个数组是:
temp1{1, 5, 5, 20}
temp2{8, 8, 2, 1}
Time: O(n) Space: O(1)
代码:
import java.util.*;
class Program {
public int[] arrayOfProducts(int[] array) {
// Write your code here.
int[] temp1 = new int[array.length];
int left = 1;
for (int i = 0; i < array.length; i++) {
temp1[i] = left;
left *= array[i];
}
int[] temp2 = new int[array.length];
int right = 1;
for (int i = array.length - 1; i >= 0; i--) {
temp2[i] = right;
right *= array[i];
}
int[] res = new int[array.length];
for (int i = 0; i < array.length; i++) {
res[i] = temp1[i] * temp2[i];
}
return res;
}
}