求一组数中的众数(多种方法)
作者:互联网
题目:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素
import java.util.Arrays;
public class Zyhhhh {
//
public static void main(String[] args) {
int[] arr = new int[]{2,2,0,2,4,0,0,0,2,2,0,0,0,0};
System.out.println("方法一:"+manyNum(arr));
System.out.println("方法二:"+manyNumRecursion(arr,0,arr.length-1));
System.out.println("方法三:"+manyNumVote(arr));
}
// 方法一,排序后,中位数就是众数
public static int manyNum(int[] arr) {
Arrays.sort(arr);
return (arr[arr.length / 2]);
}
//方法二,递归思想取得众数,分治法
public static int manyNumRecursion(int[] arr, int left, int right){
if(left == right){
return arr[left];
}
int mid = (left + right) / 2;
// 将数组分为两个半区,分别找出各个半区的众数
int leftManyNum = manyNumRecursion(arr, left, mid);
int rightManyNum = manyNumRecursion(arr, mid + 1, right);
if(leftManyNum == rightManyNum){ // 如果两个半区众数相等,直接返回,取得整个数组的众数
return leftManyNum;
}
// 比较两个半区的众数出现次数,出现次数多的就是整个数组的众数
int leftcount = numCount(arr,leftManyNum);
int rightcount = numCount(arr,rightManyNum);
return (leftcount > rightcount)? (leftManyNum):(rightManyNum);
}
public static int numCount(int[] arr, int manyNum1){
int count = 0;
for(int i : arr){
if(arr[i] == manyNum1){
count++;
}
}
return count;
}
//方法三,投票法,耗时最短
public static int manyNumVote(int[] arr){
int count = 0;
int manyNum = arr[0];
for(int i : arr){
if(count == 0){
manyNum = i;
}
// 赞成加一,反对减一
if(manyNum == i){
count++;
}else{
count--;
}
}
return manyNum;
}
}
谢谢浏览
标签:count,manyNum,arr,一组,int,众数,public,数中 来源: https://blog.csdn.net/m0_50370214/article/details/121522265