問題描述
???????對給定數(shù)組中的元素按照元素出現(xiàn)的次數(shù)排序,出現(xiàn)次數(shù)多的排在前面,如果出現(xiàn)次數(shù)相同错忱,則按照數(shù)值大小排序以清。例如眉孩,給定數(shù)組為{2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}勺像,則排序后結(jié)果為{3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}吟宦。
輸入
???????輸入的第一行為用例個數(shù)瓦阐;后面每一個用例使用兩行表示睡蟋,第一行為數(shù)組長度戳杀,第二行為數(shù)組內(nèi)容隔缀,數(shù)組元素間使用空格隔開。
輸出
???????每一個用例的排序結(jié)果在一行中輸出牵触,元素之間使用空格隔開揽思。
示例輸入
1
4
2 3 2 5
示例輸出
2 2 3 5
思路
???????略
完整代碼
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int casesnum = sc.nextInt();
while(casesnum>0){
int length = sc.nextInt();
sc.nextLine();
String[] temp = sc.nextLine().split(" ");
Map<String,Integer> count = new HashMap<String,Integer>();
for(int i=0;i<length;i++) {
if(count.containsKey(temp[i]))
count.replace(temp[i],count.get(temp[i]),count.get(temp[i])+1);
else
count.put(temp[i],1);
}
int k = 0;
while (count.size()>0) {
//map的entry接口,將各鍵值對構(gòu)建為一個對象渊鞋,組成集合
Iterator iter = count.entrySet().iterator();
int max = 0;
String maxVal = "";
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String number = (String) entry.getKey();
int counts = (int) entry.getValue();
if (counts > max) {
max = counts;
maxVal = number;
}
}
for (int j=0;j<max;j++) {
System.out.print(maxVal);
k++;
if (k<length)
System.out.print(" ");
else
System.out.println();
}
count.remove(maxVal,max);
}
casesnum --;
}
}
}