CCF记录——出现次数最多的数
来源:互联网 发布:伴随矩阵的求法 编辑:程序博客网 时间:2024/06/06 16:39
CCF记录——出现次数最多的数
先看题目:
问题描述
给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
输入格式
输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。
输出格式
输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。
样例输入
610 1 10 20 30 20
样例输出
10
自己使用的是Map
,参考答案使用的是数组,试了一下都是一百分,就都贴一下:
Map
方法:
package test;import java.util.*;public class FindMost1 { public static void main(String[] args) { Scanner keyin = new Scanner(System.in); int N = keyin.nextInt(); //获取整数的数量 Map<Integer, Integer> map = new TreeMap<>(new Comparator<Integer>() { //自定义Comparator进行从大到小比较 @Override public int compare(Integer o1, Integer o2) { return o1 - o2;//从大到小 } }); for (int i = 0; i < N; i++) { int n = keyin.nextInt(); if (map.containsKey(n)) { int count = map.get(n); count++; map.put(n, count); //利用treemap中重复建的数据会被后一个覆盖的特性 continue; } else { map.put(n, 0); } } Set<Integer> set = map.keySet(); Iterator<Integer> iterator = set.iterator(); int maxValue = -1; int result = -1; while (iterator.hasNext()) { int key = iterator.next(); int value = map.get(key); if (value > maxValue) { maxValue = value; result = key; } } System.out.println(result); }}
数组方法:
package test;import java.util.Scanner;public class FindMost2 { public static void main(String[] args) { Scanner keyIn = new Scanner(System.in); int N = keyIn.nextInt(); int[] nums = new int[10001]; for (int i = 0; i < N; i++) { int n = keyIn.nextInt(); int count = nums[n]; count++; nums[n] = count; } int maxCount = -1; int result = -1; for (int i = 10000; i >= 0; i--) { if (nums[i] >= maxCount) { maxCount = nums[i]; result = i; } } System.out.println(result); }}
0 0
- CCF记录——出现次数最多的数
- CCF—出现次数最多的数
- CCF 出现次数最多的数
- 【CCF】出现次数最多的数
- ccf 出现次数最多的数
- CCF-出现次数最多的数
- CCF认证-出现次数最多的数
- CCF 出现次数最多的数
- CCF 出现次数最多的数
- C++ CCF 出现次数最多的数
- ccf试题 出现次数最多的数
- CCF之出现次数最多的数
- CCF之出现次数最多的数
- CCF——出现最多的数
- ccf试题201312-1——出现次数最多的数
- CCF计算机软件能力认证模拟试题-出现次数最多的数(Java参考答案学习记录)
- CCF计算机软件能力认证模拟试题-出现次数最多的数(Java参考答案学习记录)
- CCF计算机软件认证题目--出现次数最多的数
- 前端工程师需要明白的「像素」
- Linux平台用C++实现信号量,同步线程
- JavaScript浅析闭包和内存泄露的问题
- C++中四种进程或线程同步互斥的控制方法
- IE为什么把火狐和Chrome给打伤了?
- CCF记录——出现次数最多的数
- SparseArray详解,我说SparseArray,你说要!
- LeetCode 278. First Bad Version(首个坏版本)
- 文件上传和下载
- 深度缓存
- 爬楼梯-lintcode
- js数组去重
- 百思不得姐数据刷新数据部分(七)
- 利用 jQuery 的 ajax 读取本地数据