問題描述: |
問題描述 給定n個正整數,找出它們中出現次數最多的數。如果這樣的數有多個,請輸出其中最小的一個。 輸入格式 輸入的第一行只有一個正整數n(1 ≤ n ≤ 1000),表示數字的個數。 輸出格式 輸出這n個次數中出現次數最多的數。如果這樣的數有多個,輸出其中最小的一個。 樣例輸入 6 樣例輸出 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);
}
}