题目:
题解:
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();
}
}