如何按大多数重复值对数组进行排序。?
suppose I have an array [3, 3, 3, 3, 4, 4]
Expected the result as [3, 4] since 3 is most repeated and 4 is least repeated.
有没有办法呢?
提前致谢....!
答案 0 :(得分:0)
这是一种方法:
distictList
:从数组中获取所有不同的值并存储在此
countArray
:对于i
distinctList
中的每个countArray[i]
索引,都会出现distinctList[i]
现在排序countArray
并同时在distinctList
上应用相同的互换。
Ex:[3,3,4,4,4]
distinctList [3,4]
countArray [2,3]
降序排序countArray [3,2]同时对distinctList进行排序[4,3] 输出:[4,3]`
答案 1 :(得分:0)
Python简单:
data = [3, 2, 3, 4, 2, 1, 3]
frequencies = {x:0 for x in data}
for x in data:
frequencies[x] = frequencies[x] + 1
sorted_with_repetitions = sorted(data, key=lambda x:frequencies[x],reverse=True)
sorted_without_repetitions = sorted(frequencies.keys(), key=lambda x:frequencies[x],reverse=True)
print(data)
print(sorted_with_repetitions)
print(sorted_without_repetitions)
print(frequencies)
相同的方法(用于收集不同值并计算出现次数的关联容器,用于自定义比较以使用原始数据或仅对不同项目对数组进行排序)适用于Java。