码迷,mamicode.com
首页 > 其他好文 > 详细

求众数

时间:2020-05-30 22:17:00      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:==   遍历数组   mamicode   max   数组元素   class   return   数组   次数   

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

技术图片

 

 

 方式一:将数组排序,取有序数组最中间的那个元素就一定是众数。(实现比较简单,不做赘述)

方法二:摩尔投票法。选取取第一个元素为target,并计数器置为1,顺序遍历数组元素,当遇到相同的元素,计数器加1;遇到不同元素时,计数器减1,当计数器减为0时,将下一个元素作为选取target,最后剩下的target元素就一定为众数。

 1  public static int getMaxNums(int[] arr) {
 2         if (arr == null || arr.length == 0) {
 3             return -1;
 4         }
 5         int target = arr[0];
 6         int count = 1;
 7         for (int i = 1; i < arr.length; i++) {
 8             if (target == arr[i]) {
 9                 count++;
10             } else {
11                 count--;
12                 if (count == 0) {
13                     target = arr[i];
14                     count = 1;
15                 }
16             }
17         }
18         return target;
19     }

 

求众数

标签:==   遍历数组   mamicode   max   数组元素   class   return   数组   次数   

原文地址:https://www.cnblogs.com/seedss/p/12994843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!