CCF201312-1:出现次数最多的数(JAVA版)

问题描述

  给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。

输入格式

  输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数。
  输入的第二行有n个整数s1, s2, …, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n)。相邻的数用空格分隔。

输出格式

  输出这n个次数中出现次数最多的数。如果这样的数有多个,输出其中最小的一个。

样例输入

6
10 1 10 20 30 20

样例输出

10

先用一个list1存储每一个MyNumber对象,MyNumber对象包括数字和这个数字出现的次数,初始化的时候,都是出现1次,比如题目中给出的

6

10 1 10 20 30 20

在list1中的体现形式就是(10 1) (1 1) (10 1) (20 1) (30 1) (20 1)

经过遍历后的list             (10 2) (1 1) (10 1) (20 2) (30 1) (20 1)

定义一个方法getMaxValue(List<MyNumber> list1) ,找到list1中次数出现最多的那个MyNumber

然后遍历list1,凡是出现次数等于获取到的maxValue的都放入list2中; 比如题目中的 (10 2)(20 2)被放入list2中

最后就是在list2中找到num最小的。得到(10 2) ,最后输出10

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {

	public static List<MyNumber> list1 = new ArrayList<MyNumber>();
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		
		//定义一个list 用于存储出现数字最多的数,如果这种数有多个就全放进去,一个就直接输出
		List<MyNumber> list2 = new ArrayList<MyNumber>();
		int x = 1;
		
		for(int i = 0;i<n;i++){
			list1.add(new MyNumber(sc.nextInt(), x));
		}
		sc.close();
		
                
                //遍历当前list1,如果后面出现相同的数字,那么次数count就+1
		for(int i = 0;i<n-1;i++){
			for(int j = i+1;j<n;j++){
				if(list1.get(i).num==list1.get(j).num){
					list1.get(i).count = list1.get(i).count + 1;
				}
			}
		}
		
		//获取出现次数最多的那个数字
		int maxValue = getMaxValue(list1);
		
		for(int i = 0;i<n;i++){
			if(list1.get(i).count==maxValue){
				list2.add(list1.get(i));
			}
		}
		int min = Integer.MAX_VALUE;
		
		if(list2.size()==1){
			min = list2.get(0).num;
		}else{
			for(int i = 0;i<list2.size()-1;i++){
				if(list2.get(i).num<min){
					min = list2.get(i).num;
				}
			}
		}
		System.out.println(min);

	}

	private static int getMaxValue(List<MyNumber> list1) {
		int max = 0;
		for(int i = 0;i<list1.size();i++){
			if(list1.get(i).count>max){
				max = list1.get(i).count;
			}
		}
		return max;
	}
}

class MyNumber{
	int num ;//表示数字
	int count;//该数字出现的次数
	
	public MyNumber(int num,int count){
		this.num = num;
		this.count = count;
	}
	
	@Override
	public String toString() {
		
		return this.num +" "+ this.count;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_39464426/article/details/88088861