ccf csp认证 201503-2 java 数字排序 100分
代码能力较差,希望可以得到大家的指导。一起努力,一起进步。
这道题,我用了map来储存数字。并且根据map中的value对map排序。
推荐大家看这篇博文,我找了几篇,这个不错。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if(map.containsKey(a[i])){
int count = map.get(a[i])+1;
map.put(a[i], count);
}else{
map.put(a[i], 1);
}
}
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1,
Entry<Integer, Integer> o2) {
// TODO Auto-generated method stub
return o2.getValue().compareTo(o1.getValue());
}
});
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getKey() + " " + list.get(i).getValue());
}
}
}