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

package tmfon;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();// 所輸入的正整數個數
		Map<Integer, Integer> m = new HashMap<Integer, Integer>();// 儲存正整數出現次數
		int num = 0;// 暫時保存輸入正整數值
		int result;// 輸出的結果
		for (int i = 0; i < n; i++) {
			num = sc.nextInt();
			if (m.containsKey(num))// 判斷該正整數出現過
				m.put(num, m.get(num) + 1);// 是,則出現次數遞增
			else
				m.put(num, 1);// 否,存儲並置出現次數爲1
		}
		result = num;// 將最後輸入的正整數待定爲結果
		for (Map.Entry<Integer, Integer> e : m.entrySet())// 遍歷此集合
		{
			if (m.get(result) < e.getValue())// 出現次數不同時
				result = e.getKey();
			else if (m.get(result) == e.getValue() && result > e.getKey())// 出現次數相同時
				result = e.getKey();
		}
		System.out.println(result);
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章