题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路分析
运用摩尔投票思想或者可以叫做阵地攻守思想
用count来统计元素出现的次数,用num记录某个元素。遍历数组,当array[i]和num相同时count++,不同时count–,当count又为0时,将此时的array[i]作为新的num值。遍历结束,将count置0,再重新扫描数组,计算与num值相同的元素个数,若大于length/2,则返回num值,否则返回0。
PS:王道的数据结构上也有相似题目
代码实现
public int MoreThanHalfNum_Solution(int [] array) {
/*
int count = 1, num = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] != num) {
if(count>0){
count--;
}else if (count <= 0) {
num = array[i];
}
} else {
count++;
}
}
*/
int count = 0, tmp = 0;
for (int i = 0; i < array.length; i++) {
if (count == 0) {
tmp = array[i];
count++;
} else {
count = array[i] == tmp ? count + 1 : count - 1;
}
}
return count;
}