PTA (JAVA-求整数序列中出现次数最多的数)

it2025-04-17  4

JAVA-求整数序列中出现次数最多的数

要求统计一个整型序列中出现次数最多的整数及其出现次数。

输入格式: 在一行中给出序列中整数个数N(0<N≤1000),依次给出N个整数,每个整数占一行。

输出格式: 在一行中输出出现次数最多的整数及其出现次数,数字间以空格分隔。题目保证这样的数字是唯一的。

输入样例: 在这里给出一组输入。例如: 10 3 2 -1 5 3 4 3 0 3 2

输出样例: 在这里给出相应的输出。例如:

3 4

这道题只需要建立一个HashMap<Integer,Integer>容器,当Key值已经存在容器时取出Value值+1在放回去。否则就直接Value值为1。最后遍历一遍HashMap容器找出出现次数最多的数,记录输出即可。

import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); HashMap<Integer,Integer> m = new HashMap<>(); int n = cin.nextInt(); for(int i = 0;i < n;i++){ int x = cin.nextInt(); if(m.containsKey(x)){ m.put(x,m.get(x)+1); } else{ m.put(x,1); } } int k = 0,sum = 0; for(Map.Entry<Integer,Integer> entry: m.entrySet()){ int x = entry.getKey(); int y = entry.getValue(); if(y > sum){ k = x; sum = y; } } System.out.println(k+" "+sum); } }
最新回复(0)