题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
如果不存在则输出0。
解法一:有一个数字出现的次数超过数组长度的一半。那么如果面对一个已经排序的数组,加入存在这个数字,那么这个数字必然位于中位数,所以我们可以首先对数组进行排序,然后在对其中位数进行判定
代码如下:
public int MoreThanHalfNum_Solution(int[] array) {
if (array == null || array.length < 1) {
return 0;
}
Arrays.sort(array);
int result = array[array.length / 2];
int count = 0;
for (int i = 0; i < array.length; i++) {
if (result == array[i]){
count ++;
}
if (count > array.length / 2){
return result;
}
}
return 0;
}
解法二:一个数字出现的次数如果超过数组长度的一半,那么如果我们举一个极限的例子,加入一个长度为9的数组,内有5个2,剩下为1, 3, 4, 5,排列为:2, 1, 2, 3, 2, 4, 2, 5, 2, 那么我们从数组的开头开始,取times = 0; result = numbers[0], 如果在遍历数组的过程中,与result相同则times++,不相同times--,times为0则将result设为当前遍历的值,那么如果存在数字出现的次数大于数组长度的一半,则result一定是这个数字,所以最后我们需要对其进行检验。
代码如下:
public int MoreThanHalfNum_Solution2(int[] array) {
if (array == null || array.length < 1) {
return 0;
}
int times = 1;
int result = array[0];
for (int i = 0; i < array.length; i++) {
if (times == 0){
result = array[i];
times = 1;
} else if (result == array[i]){
times ++;
}else{
times --;
}
}
int count = 0;
for (int i = 0; i < array.length; i++) {
if (result == array[i]){
count ++;
}
if (count > array.length / 2){
return result;
}
}
return 0;
}