题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
分析:
首先题目中要求的数字需要超过数组的一般长度,那么其在数组中是最多的,我们可以先求得数组中最多的数,然后判断其是否超过数组的一半,
设置两个计数器1和2,1负责每次统计每个数出现的个数,2负责将比上次多的个数保存,设置一个缓存负责保存目前数量最多的数,
每次统计完之后与上次的进行比较,判断是否需要对计数器2和缓存进行更新。
通过排序可以进一步对算法进行优化,
代码示例
public static int search (int [] arr){
Arrays.sort(arr);
int len = arr.length;
int other = 0;
int large = 0;
int count = 0;
int j = 0;
for (int i=0;i<len/2;i+=other){
other =0;
for (j=i;j<len;j++){
if (arr[i]==arr[j]){
other++;
}else {
break;
}
}
if (other>large){
large = other;
// other =0;
count=arr[i];
}else {
continue;
}
}
if (large > len/2){
return count;
}
return 0;
}