How to arrange an array in decreasing order of frequency of each number?

前端 未结 7 526
一整个雨季
一整个雨季 2021-01-03 04:23

Input : {5, 13, 6, 5, 13, 7, 8, 6, 5}

Output : {5, 5, 5, 13, 13, 6, 6, 7, 8}

The question is to arrange the numbers in the array in

7条回答
  •  孤街浪徒
    2021-01-03 04:57

    private static void sortByFrequency(int[] a)
    {
        Map map = new HashMap();
        for(int i=0; i set = map.keySet();
        TreeSet treeSet = new TreeSet();
        for(int i : set)
        {
            treeSet.add(map.get(i));
        }
    
        for(Element e : treeSet)
        {
            for(int i=0; i
    {
        private final int index;
        private int frequency;
    
        Element(int index)
        {
            this.index = index;
            this.frequency = 1;
        }
    
        @Override
        public int compareTo(Element o)
        {
            int k = o.frequency - this.frequency;
            if(k != 0) return k;
            else
            {
                return this.index - o.index;
            }
        }
    }
    
    public static void main(String[] args)
    {
        int[] a = {5, 13, 6, 5, 13, 7, 8, 6, 5};
        sortByFrequency(a);
    }
    

提交回复
热议问题