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

前端 未结 7 525
一整个雨季
一整个雨季 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 05:02

    C#. It takes the most obvious approach: sort by frequency and ordinal.

    Output: 5 5 5 13 13 6 6 7 8. Space: O(n). Time: O(n log n).

    class Program
    {
        class FreqAndOrdinal
        {
            public int Frequency;
            public int Ordinal;
            public FreqAndOrdinal(int freq, int ord)
            {
                this.Frequency = freq;
                this.Ordinal = ord;
            }
        }
    
        static int Compare(FreqAndOrdinal x, FreqAndOrdinal y)
        {
            int result = y.Frequency.CompareTo(x.Frequency);
            return result == 0 ? x.Ordinal.CompareTo(y.Ordinal) : result;
        }
    
        static void Main(string[] args)
        {
            int[] nums = new int[] { 5, 13, 6, 5, 13, 7, 8, 6, 5 };
            var freqLookup = new Dictionary<int, FreqAndOrdinal>(nums.Length);
            for (int i = 0; i < nums.Length; i++)
            {
                FreqAndOrdinal tmp;
                if (freqLookup.TryGetValue(nums[i], out tmp))
                    ++tmp.Frequency;
                else
                    freqLookup[nums[i]] = new FreqAndOrdinal(1, i);
            }
    
            Array.Sort(nums, (x,y) => Compare(freqLookup[x], freqLookup[y]));
    
            for (int i = 0; i < nums.Length; i++)
            {
                Console.Write(" {0}", nums[i]);
            }
            Console.ReadKey();
        }
    }
    
    0 讨论(0)
提交回复
热议问题