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

前端 未结 7 563
一整个雨季
一整个雨季 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:42

    I can think of two solutions:

    Make a first pass to count frequencies and store the first index and then sort according to that

    This is simple to implement, uses linear (O(N)) additional memory in the worst case and takes O(N log N) time.

    Do everything in one pass with some sort of priority queue, where the "priority" is the frequency count (changing as you pass through the input), and the index of the first occurrence to break ties

    This does everything in a single pass, but I can't think of any advantage over the other solution. It still requires O(N) additional memory, and will also take O(N log N) time. Also, it requires a more complex data structure.

提交回复
热议问题