28.数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
题目解答
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { int length=array.length; //判断是不是有效的数组 if(array==null || length<=0){ return 0; } //count计数,找出出现次数最大的数 int res=array[0]; int count=1; for(int i=1;i<length;i++){ if(count==0){ res=array[i]; count=1; }else if(array[i]==res){ count++; }else{ count--; } } //判断输入数组中频率最高的数字有没有超过数组的一半 count=0; for(int i=0;i<length;i++){ if(array[i]==res){ count++; } } if(count*2>length){ return res; } return 0; } }

浙公网安备 33010602011771号