package sort;
public class Test39 {
public static void main(String[] args) {
int[]s={1,1,1,1,1,1,1,1,2,3,2,2,2,5,4,2};
System.out.println(findMoreThanHalf(s));
}
public static int findMoreThanHalf(int[]a){
int number=a[0];//先预定数组中第一个数为目标数字
int count=1;
for(int i=1;i<a.length;i++){
if(a[i]==number) count++;//如果重复出现则count加1 ,
if(a[i]!=number){//如果出现的数字不等于目标数
if(count==0){//如果count为0 则把当前数设为目标数
number=a[i];
continue;
}
count--;//count不为0则count--;
}
}
return number;
}
}
寻找众数的算法实现
本文介绍了一种在数组中寻找出现次数超过一半的众数的算法。通过遍历数组,利用计数的方式,最终找到可能的众数并返回。此算法在数据处理和算法设计中有广泛应用。
675

被折叠的 条评论
为什么被折叠?



