CSP201503-2(數字排序)(Java100分)
阿新 • • 發佈:2018-11-22
問題描述
給定n個整數,請統計出每個整數出現的次數,按出現次數從多到少的順序輸出。
輸入格式
輸入的第一行包含一個整數n,表示給定數字的個數。
第二行包含n個整數,相鄰的整數之間用一個空格分隔,表示所給定的整數。
輸出格式
輸出多行,每行包含兩個整數,分別表示一個給定的整數和它出現的次數。按出現次數遞減的順序輸出。如果兩個整數出現的次數一樣多,則先輸出值較小的,然後輸出值較大的。
樣例輸入
12
5 2 3 3 1 3 4 2 5 2 3 5
樣例輸出
3 4
2 3
5 3
1 1
4 1
評測用例規模與約定
1 ≤ n ≤ 1000,給出的數都是不超過1000的非負整數。
思路:這個題我為了少寫一個類,費了很大功夫。先用map儲存每個數字出現的次數,然後把map變為集合,然後把集合變為陣列,再對陣列排序,陣列排序的時候自己寫了一個比較器。
map內建了一個類Entry,所以轉換成集合時也是Entry型別的陣列。這種方法歡迎大家嘗試。
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
Map<Integer, Integer> map = new HashMap<>();
for (int i=0;i<n;i++) {
int temp = sc.nextInt();
if(map.containsKey(temp)) {
map.replace(temp, map.get(temp)+1);
}
else {
map.put(temp, 1);
}
}
Entry<Integer,Integer>[] en =new Entry[map.size()];
map.entrySet().toArray(en);
Arrays.sort(en,new com());
for(int i=0;i<en.length;i++) {
System.out.println(en[i].getKey()+" "+en[i].getValue());
}
}
}
class com implements Comparator<Entry<Integer,Integer>>{
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
// TODO Auto-generated method stub
int t = o1.getValue()-o2.getValue();
if(t!=0) {
return -t;
}
else {
return o1.getKey()-o2.getKey();
}
}
}