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

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

    Sort the array, and in your sort function for x, y: sort by count(x) vs. count(y). If they are the same, sort by index(x) vs. index(y)

    In python:

    input = [5, 13, 6, 5, 13, 7, 8, 6, 5]
    orig = list(input)
    
    def cmp(x, y):
        if (orig.count(y) - orig.count(x) != 0):
            return orig.count(y) - orig.count(x)
        return orig.index(x) - orig.index(y)   
    
    input.sort(cmp) 
    print input
    

    To make it more efficient, precalculate counts and indexes before sorting the array.

提交回复
热议问题