配列内の左加算と右加算の和に等しい数値を見つけます.
6871 ワード
public static void demo1(int arr[]){
int length = arr.length;
int leftTotal = 0;
int rightTotal = 0;
for(int i=1;iif(i==1){
leftTotal = arr[0];
for(int j=i+1;jelse{
leftTotal = leftTotal+arr[i-1];
rightTotal = rightTotal-arr[i];
}
System.out.println("===>i="+i+"=====>leftTotal="+leftTotal+"=====>rightTotal="+rightTotal);
if(leftTotal == rightTotal){
System.out.println(arr[i]);
}
}
}
public static void splitFind(int arr[]){
int length = arr.length;
int head,tail,index;
head = 0;
tail = length - 1; //
index = length / 2;//
int total = 0; //
for(int i :arr){
total += i;
}
do{
int leftTotal = 0;
//
for(int le = 0;le <index ;le ++){
leftTotal += arr[le];
}
// -
int doubleValue=(total - arr[index]);
if(leftTotal*2 index;
index = index + (length - index) / 2;
}else if(leftTotal*2 >doubleValue){
total = index;
index = head + (index - head) / 2;
}else{
System.out.println(index);
return ;
}
}while(index > head && index
以上のアルゴリズムの除算と乗算は変位演算に最適化されている.
public static void splitFind2(int arr[]){
int length = arr.length;
int head,tail,index;
head = 0;
tail = length - 1; //
index = length >> 1;//
int total = 0; //
for(int i :arr){
total += i;
}
do{
int leftTotal = 0;
//
for(int le = 0;le <index ;le ++){
leftTotal += arr[le];
}
// -
int doubleValue=(total - arr[index]);
if(leftTotal<<1 index;
index = index + (length - index) >>1;
}else if(leftTotal<<1 >doubleValue){
total = index;
index = head + (index - head) >>1;
}else{
System.out.println(index);
return ;
}
}while(index > head && index