按频率值对数组项进行排序 [英] Sorting array items by frequency value

查看:67
本文介绍了按频率值对数组项进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种很好的方法或算法可以根据每个项目中的频率值对数组进行排序?假设我有这个数组:
[3、3、3、5、6、12、5、5、6].我希望输出为[3、5、6、12].我当时在考虑诸如插入排序之类的事情,但我相信可能会有一种更简单的方法.

is there a good way or algorithm to sort an array by the value of a frequency in each item? Let's say I have this array:
[3, 3, 3, 5, 6, 12, 5, 5, 6]. I want the output to be [3, 5, 6, 12]. I was thinking about something like insertionsort but I belive that there could be an easier way.

推荐答案

好吧,您明确需要每个元素的计数,即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

这篇关于按频率值对数组项进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆