題目:
題解:
1. 題解一:左右數組
- 解釋一:
- 解釋二:
2. 題解二:左(或右)數組
- 解釋一:
- 解釋二:
代碼:
1. 代碼一:左右數組
public class 面試題66 {
// 方法1:左右數組
public static int[] constructArr(int[] a) {
if(a == null || a.length == 0)
{
return a;
}
int len = a.length;
int left[] = new int[len];
int right[] = new int[len];
left[0] = 1;
right[len - 1] = 1;
for(int i = 1; i < len; i++)
{
left[i] = left[i - 1] * a[i - 1];
}
for(int i = len - 2; i >= 0; i--)
{
right[i] = right[i + 1] * a[i + 1];
}
int ans[] = new int[len];
for(int i = 0; i < len; i++)
{
ans[i] = left[i] * right[i];
}
return ans;
}
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5 };
int res[] = constructArr(a);
for(int i = 0; i < res.length; i++)
{
System.out.print(res[i] + " ");
}
System.out.println();
}
}
2. 代碼二:左(或右)數組
public class 面試題66 {
// 方法2:左(或右)數組
public static int[] constructArr(int[] a) {
int ans[] = new int[a.length];
int cur = 1;
for(int i = 0; i < a.length; i++)
{
ans[i] = cur; // 先乘左邊的數(不包括自己)
cur *= a[i];
}
cur = 1;
for(int i = a.length - 1; i >= 0; i--)
{
ans[i] *= cur; // 再乘右邊的數(不包括自己)
cur *= a[i];
}
return ans;
}
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5 };
int res[] = constructArr(a);
for(int i = 0; i < res.length; i++)
{
System.out.print(res[i] + " ");
}
System.out.println();
}
}