求數組的平衡點

原文見:[url]http://www.iteye.com/topic/600079[/url]
平衡點:比如int[] numbers = {1,3,5,7,8,25,4,20}; 25前面的總和爲24,25後面的總和也是24,25這個點就是平衡點;假如一個數組中的元素,其前面的部分等於後面的部分,那麼這個點的位序就是平衡點
要求:返回任何一個平衡點
思路:數組兩邊同時求和,只需一次遍歷數組,統計求和次數count,如果count爲數組長度-1,那麼存在平衡點。
寫篇日記,記錄一下自己的代碼:
bug是,{1,0,0,0,1}存在多個平衡點,下面的程序只能找到中間的0;{1,0,0,1}有2個平衡點,下面的程序卻找不到。其他的bug還沒有發現。

public static void getBalancePoint(int[] arg){
if(arg==null){
System.out.println("array is null...");
return;
}
if(arg.length<3){
System.out.println("array's length is smaller than 3...no balance...");
return;
}
if(arg.length==3){
if(arg[0]==arg[2]){
System.out.println("array's balance is : "+arg[1]);
}else{
System.out.println("array has no balance...");
}
return;
}
int totalHead=0; //前部分總和(假設數組下標小的部分表示前)
int totalEnd=0; //後部分總和
int head=0; //前部分的數組下標
int end=arg.length-1; //後部分的數組下標
boolean addHead=true; //是否累加前部分
boolean addEnd=true; //是否累加後部分
int addCount=0; //總共累加次數
while(head<end){
if(addHead){ //前部分依次累加
totalHead+=arg[head];
addCount++;
}
if(addEnd){ //後部分依次累加
totalEnd+=arg[end];
addCount++;
}
if(totalHead<totalEnd){ //只允許前部分累加
head++;
addHead=true;
addEnd=false;
}else if(totalHead>totalEnd){ //只允許後部分累加
end--;
addHead=false;
addEnd=true;
}else{ //前後同時累加
head++;
end--;
addHead=true;
addEnd=true;
}
} //end while
if(addCount==(arg.length-1)){ //存在平衡點
System.out.println("array's balance is : "+arg[head]);
}else{
System.out.println("array has no balance...");
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章