数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他数字出现的次数和还要多。可以考虑在遍历数组的时候保存两个值:数组中的数字,次数。当下一次遍历的数字与保存数字相同时,次数加一;不同,减一;当次数为0时,保存下一次遍历的数字,并将次数置为一。
由于我们要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。
(另外要注意后面的检查部分,该数字是不是出现了超过数组的一半长度)
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if (array.length == 0) return 0;//异常情况
int num = 0;//保存数字
int res = 0;//保存次数
//遍历数组
for(int i = 0; i < array.length; i++) {
//如果次数为0,保存数字,次数置为1
if(num == 0) {
res = array[i];
num = 1;
}
//次数不为1,当前数字与保存的数字相同时,次数加1
else if (array[i] == res) {
num++;
}
//当前数字与保存的数字不同时,次数减1
else if (array[i] != res) {
num--;
}
}
//如果数组中没有任何一个数字出现的次数超过一半数组长度,返回0
int count = 0;
for(int i = 0; i < array.length; i++) {
if (array[i] == res) {
count++;
}
}
if (count > array.length/2) return res;
else return 0;
}
}