就用除法
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] answer = new int[nums.length];
int sum = 1;
int zeroNum = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == 0) zeroNum++;
sum *= nums[i];
answer[i] = 0;//初始化
}
if (zeroNum >= 2){
return answer;
}else if(zeroNum == 1){
sum = 1;
for (int i = 0; i < nums.length; i++){
if (nums[i] == 0){
for (int j = 0; j < nums.length; j++){
if (j != i){
sum *= nums[j];
}
}
answer[i] = sum;
break;
}
}
}else{
for (int i = 0; i < nums.length; i++){
answer[i] = sum / nums[i];
}
}
return answer;
}
}
前缀、后缀
class Solution {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] L = new int[length]; //存放对应元素左侧的乘积
int[] R = new int[length]; //存放对应元素右侧的乘积
int num = 1;
L[0] = 1;
for (int i = 1; i < length; i++){
L[i] = L[i - 1] * nums[ i - 1];
}
num = 1;
R[length - 1] = 1;
for (int j = length - 2; j >= 0; j--){
R[j] = R[j + 1] * nums[j + 1];
}
int[] answer = new int[length];
for (int i = 0; i < length; i++){
answer[i] = R[i] * L[i];
}
return answer;
}
}
上述方法的改进,L R 和 answer可以公用一个数组,内存占用可以少个2M
class Solution {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] L = new int[length]; //存放对应元素左侧的乘积
//int[] R = new int[length]; //存放对应元素右侧的乘积
int num = 1;
L[0] = 1;
for (int i = 1; i < length; i++){
L[i] = L[i - 1] * nums[ i - 1];
}
num = 1;
//R[length - 1] = 1;
int Rtemp = 1;
for (int j = length - 2; j >= 0; j--){
//R[j] = R[j + 1] * nums[j + 1];
Rtemp = Rtemp * nums[j + 1];
L[j] *= Rtemp;
}
// int[] answer = new int[length];
// for (int i = 0; i < length; i++){
// answer[i] = R[i] * L[i];
// }
return L;
}
}
标签:150,nums,int,++,面试,length,answer,new,十四
From: https://www.cnblogs.com/poteitoutou/p/18011004