统计出现次数最多的数
来源:互联网 发布:像牲口一样活下去 知乎 编辑:程序博客网 时间:2024/05/17 10:41
问题描述:
给定n个正整数,找出他们中出现次数最多的数,如果这样的数有多个,请输出其中最小的一个数:
样例:
6(数列长度)
10 1 10 20 30 20(数列)
输出:10
思路:先对数组进行排序,然后将数组中的数据和数据出现的次数存放到HashMap中,最后遍历这张哈希表,输出结果。
下面给出程序:
import java.util.Arrays;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Scanner;public class Main {public static void main(String[] args) {// TODO Auto-generated method stubScanner s=new Scanner(System.in);int k=s.nextInt();int[] num=new int[k];for(int i=0;i<k;i++){num[i]=s.nextInt();}/*for(int i:num){System.out.println(i);}*/System.out.println(dosth(num));}public static int dosth(int[] array){int m=0;int p=0;Arrays.sort(array);Map nums = new HashMap();nums.put(m,0);for (int i = 0; i < array.length; i++) { if (m == array[i]) { int v = (Integer) nums.get(m); v++; nums.put(m, v); } else { nums.put(array[i], 1); } m = array[i];} Iterator iterator = nums.keySet().iterator(); int maxNumber = 0;//次数 int maxValue=0;//数组的值 while(iterator.hasNext()) { int key = (Integer)iterator.next();//获得键 int value = (Integer)nums.get(key);//获得值 if((value>maxNumber)||(maxValue>key))//如果出现的次数比前面的项多 { maxNumber = value; maxValue= key; } } return maxValue;}}注意
if((value>maxNumber)||(maxValue>key))这个的使用
0 0
- 统计出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 出现次数最多的数
- 统计出现次数最多的程序
- 统计连续出现次数最多的单词
- 统计出现次数最多的数据
- 找出出现次数最多的数
- Cookie获取最后一次访问时间(浏览器第一次打开的时候是没有cookie的)
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- MySQL Delete、Truncate、updateDelete
- 小试2解析
- [BZOJ2541][Ctsc2000]冰原探险(bfs)
- 统计出现次数最多的数
- HTML
- c语言求最大公约数
- Linux学习笔记
- HTTP请求和响应过程
- 组件编写1-----使用JQ生成组件
- git上传本地代码到github(最简单方法,不用配置ssh)
- 获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列。
- easeui自定义消息布局---小米