题目
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路
1 首先找出出现次数最多的数字
2 然后统计出现次数最多的数字是否超过数组长度的一半。
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int len=array.length;
if(len==0) return 0;
int temp=array[0];
int count=1;
//找出出现次数最多的数字
for(int i=1;i<array.length;i++){
if(array[i]==temp)
count++;
else
count--;
if(count==0){
count=1;
temp=array[i];
}
}
count=0;
for(int i=0;i<len;i++)
if(array[i]==temp)
count++;
return count*2>len? temp:0;
}
}
其他的题题解
剑指offer题解 java版