CCF记录——出现次数最多的数

来源:互联网 发布:伴随矩阵的求法 编辑:程序博客网 时间:2024/06/06 16:39

CCF记录——出现次数最多的数

先看题目:

标题 内容 试题名称 出现最多的数 时间限制 1.0s 内存限制 256m

问题描述

给定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
原创粉丝点击