首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法训练 出现次数最多的整数

算法训练 出现次数最多的整数

作者头像
AI那点小事
发布2020-04-20 17:57:24
7180
发布2020-04-20 17:57:24
举报
文章被收录于专栏:AI那点小事AI那点小事

问题描述   编写一个程序,读入一组整数,这组整数是按照从小到大的顺序排列的,它们的个数N也是由用户输入的,最多不会超过20。然后程序将对这个数组进行统计,把出现次数最多的那个数组元素值打印出来。如果有两个元素值出现的次数相同,即并列第一,那么只打印比较小的那个值。   输入格式:第一行是一个整数N,N £ 20;接下来有N行,每一行表示一个整数,并且按照从小到大的顺序排列。   输出格式:输出只有一行,即出现次数最多的那个元素值。 输入输出样例 样例输入 5 100 150 150 200 250 样例输出 150

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

class Int{
    private int N;
    private int[] Num;
    private HashMap<Integer, Integer> map;
    private int Max;
    private ArrayList<Integer> set;

    public Int() {
        super();
        Scanner in = new Scanner(System.in);
        N = in.nextInt();
        this.map = new HashMap<Integer, Integer>();
        this.set = new ArrayList<Integer>();
        this.Num = new int[N];
        Max = 0;
        int cnt = 0;
        if ( N > 0 && N <= 20){
            for ( int i = 0 ; i < N ; i++){
                this.Num[i] = in.nextInt();
                if (this.map.containsKey(this.Num[i])){
                    this.map.replace(this.Num[i],this.map.get(this.Num[i]),this.map.get(this.Num[i])+1);
                    cnt = this.map.get(Num[i]);
                    if ( this.Max < cnt){
                        this.Max = cnt;
                    }
                }else{
                    this.map.put(this.Num[i],1);
                    cnt = 1;
                    if ( this.Max < cnt){
                        this.Max = cnt;
                    }
                    set.add(this.Num[i]);
                }
            }
        }else{
            set.add(0);
        }
        in.close();
    }

    public void  FindMax(){
        ArrayList<Integer> max = new ArrayList<Integer>();
        for ( int i = 0 ; i < this.set.size(); i++){
            if ( this.map.get(set.get(i)) == this.Max){
                max.add(set.get(i));
            }else{
                continue;
            }
        }
        int[] tmp = new int[max.size()];
        for ( int i = 0 ; i < tmp.length ; i++){
            tmp[i] = max.get(i);
        }
        Arrays.sort(tmp);
        System.out.print(tmp[0]);
    }
}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Int int1 = new Int();
        int1.FindMax();
    }
}

(PS:有bug找不出来了)

这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档