数组中出现次数超过一半的数字
##题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路
使用pre记录上一次访问的值,count表明当前值出现的次数,下一个值和当前值相同count++,不同count--,减到0时更新pre,如果存在超过数组长度一半的值,那么最后pre一定会是该值(也可能不存在)。
时间复杂度O(n),空间复杂度O(1)。
代码
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array == null || array.length == 0) return 0;
int count = 1;
int pre = array[0];
for(int i = 1; i < array.length; i++) {
if(array[i] == pre) {
count++;
} else {
count--;
if(count == 0) {
pre = array[i];
count = 1;
}
}
}
count = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] == pre) {
count++;
}
}
return count > array.length / 2 ? pre : 0;
}
}