数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
首先用一个数字survivor来保存幸存者方,用一个数字count来计算幸运者幸运值 规则:如果遇到相同数字代表相同阵营,count++; 如果遇到不同数字,则幸存者count--; 如果count=0,则幸存者被取代.
public int MoreThanHalfNum_Solution(int [] array) {
int survivor=array[0];
int count=1;
for(int i=1;i<array.length;i++){
if (array[i]==survivor)
count++;
else if (array[i]!=survivor){
count--;
}
//当count=0,保存下一个数
if ( count == 0 ){
survivor = array [i];
count = 1 ;
}
}
count=0;
for(int i=0;i<array.length;i++){
if (array[i]==survivor){
count++;
}
}
if (count>array.length/2){
return survivor;
}else {
return 0;
}
}