且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按频率值对数组项进行排序

更新时间:2023-02-05 13:58:23

好吧,您明确需要每个元素的计数,即O(n).然后,您可以从中创建一个唯一列表(假设它具有m个元素),然后根据您喜欢的任何排序算法,根据频率对其进行排序.它将是O(n + mlog(m)).例如在python中:

Well, you definetly need the count for each element, which is O(n). Then you can make a unique list from it (let's say it has m elements), and sort it according to the frequency with any sorting algo, you like. It will be O(n+mlog(m)). For example in python:

from collections import Counter

myList = ['a', 'b', 'b', 'a', 'b', 'c']

myCounter = Counter(myList)
myUniqueList = list(myCounter)
sorted(myUniqueList, key=lambda e: myCounter[e])

根据Paddy3118的评论进行编辑

Editted according to Paddy3118 's comment