数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
public int MoreThanHalfNum_Solution(int [] array) {
int len = array.length;
if (array == null || len == 0)
return 0;
int result = array[0];
int times = 1;
for (int i = 1; i < len; i++) {
if (result == array[i])
times++; //同元素则times加1,不同元素则times减一
else
times--; //此处循环结束,可以知道哪个是主元素,即出现一半或者超过一半频率的,存在result中
if (times == 0) {
result = array[i];
times = 1;
}
}
times = 0;
for (int i = 0; i < len; i++) { //已经知道谁是主元素,再遍历数组得出元素的出现次数
if (result == array[i])
times++;
}
if (times * 2 <= len) //注意是<=,出现次数要超过一半才行
return 0;
return result;
}
浙公网安备 33010602011771号