import java.util.*; import java.util.Map.Entry; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); while(in.hasNext()){ int N = in.nextInt(); int K = in.nextInt(); HashMap<String, Integer> map = new HashMap<>(); for(int i = 0; i < N; i++){ String cur = in.next(); int num = map.getOrDefault(cur, 0); num++; map.put(cur, num); } Set<Map.Entry<String,Integer>> mapEntries = map.entrySet(); List<Map.Entry<String,Integer>> aList = new LinkedList<Map.Entry<String,Integer>>(mapEntries); Collections.sort(aList, new Comparator<Entry<String,Integer>>() { public int compare(Map.Entry<String,Integer>e1,Map.Entry<String,Integer>e2){ int re = e2.getValue().compareTo(e1.getValue()); if(re!=0){return re;} else{return e1.getKey().compareTo(e2.getKey());} } }); for(int i=0;i<K;i++){ System.out.printf("%s %d\n", aList.get(i).getKey(), aList.get(i).getValue()); } List<Map.Entry<String,Integer>> bList = new LinkedList<Map.Entry<String,Integer>>(mapEntries); Collections.sort(bList, new Comparator<Entry<String,Integer>>() { public int compare(Map.Entry<String,Integer>e1,Map.Entry<String,Integer>e2){ int re = e1.getValue().compareTo(e2.getValue()); if(re!=0){return re;} else{return e1.getKey().compareTo(e2.getKey());} } }); for(int i=0;i<K;i++){ System.out.printf("%s %d\n", bList.get(i).getKey(), bList.get(i).getValue()); } } } }
全部评论
(1) 回帖