Topic:
Given an integer array, returns the multiplier group that does not contain this location.
For example: arr=[2,3,1,4], return [12,8,24,6], that is, in addition to their own, other places of the class multiplication.
Requirements:
1. Time complexity is O (N).
2. Additional space complexity is O (1) In addition to the array of results that need to be returned.
Using Division:
The resulting array is recorded as Res, and the product of all numbers is recorded as all. If the array does not contain 0, set Res[i]=all/arr[i]. If there is a 0 in the array, the position of the unique arr[i]==0 is Res[i]=all, and the other locations are 0. If the number of 0 in the array is greater than 1, then the value at all positions in the res is 0.
Public Static int [] Product1 (int[] arr) {
if Null | | Arr.length < 2) {
return null;
}
int count = 0;
int all = 1;
for (int i = 0; I! = Arr.length; i++) {
if (arr[i]! = 0) {
All *= arr[i];
Else {
count++;
}
}
int New int [Arr.length];
if (count = = 0) {
for (int i = 0; I! = Arr.length; i++) {
Res[i] = All/arr[i];
}
}
if (count = = 1) {
for (int i = 0; I! = Arr.length; i++) {
if (Arr[i] = = 0) {
Res[i] = all;
}
}
}
return Res;
}
Do not use division:
1. Generate two new arrays of the same length as arr lr[] and rl[],lr[i]=arr[0...i],rl[i]=arr[i ... N-1].
2.RES[I]=LR[I-1]*RL[I+1]
3.res[0]=rl[1],res[n-1]=lr[n-2]
There are two additional arrays, which can be omitted by the RES array reuse, first the RES array as an array of auxiliary computations, and then the res is adjusted to the result array to return.
Public Static int [] product2 (int[] arr) {
if Null | | Arr.length < 2) {
return null;
}
int New int [Arr.length];
Res[0] = arr[0];
for (int i = 1; i < arr.length; i++) {
Res[i] = res[i-1] * Arr[i];
}
int tmp = 1;
for (int i = arr.length-1; i > 0; i--) {
Res[i] = res[i-1] * TMP;
TMP *= Arr[i];
}
RES[0] = tmp;
return Res;
[algorithm] does not contain the multiplier group for the value of this position