按照数值个数排序

2019-11-23  本文已影响0人  asdfgjsrgdf

问题描述

       对给定数组中的元素按照元素出现的次数排序,出现次数多的排在前面,如果出现次数相同,则按照数值大小排序。例如,给定数组为{2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12},则排序后结果为{3, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5}。

输入

       输入的第一行为用例个数;后面每一个用例使用两行表示,第一行为数组长度,第二行为数组内容,数组元素间使用空格隔开。

输出

       每一个用例的排序结果在一行中输出,元素之间使用空格隔开。

示例输入

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接口,将各键值对构建为一个对象,组成集合
                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 --;
        }

    }
}
上一篇 下一篇

猜你喜欢

热点阅读