我无法想象这之前没有人问过这个问题,但我已经搜索了各个地方,却找不到答案。
我有一个可迭代对象,其中包含重复元素。我想计算每个元素在此可迭代对象中出现的次数,并返回第 n 个最频繁出现的元素。
我有一个可以完成这个任务的工作代码,但我确实怀疑它是否是实现这个任务最优方式。
use std::collections::{BinaryHeap, HashMap};
// returns n-th most frequent element in collection
pub fn most_frequent<T: std::hash::Hash + std::cmp::Eq + std::cmp::Ord>(array: &[T], n: u32) -> &T {
// intialize empty hashmap
let mut map = HashMap::new();
// count occurence of each element in iterable and save as (value,count) in hashmap
for value in array {
// taken from https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry
// not exactly sure how this works
let counter = map.entry(value).or_insert(0);
*counter += 1;
}
// determine highest frequency of some element in the collection
let mut heap: BinaryHeap<_> = map.values().collect();
let mut max = heap.pop().unwrap();
// get n-th largest value
for _i in 1..n {
max = heap.pop().unwrap();
}
// find that element (get key from value in hashmap)
// taken from https://dev59.com/uLjna4cB1Zd3GeqP5y4z
map.iter()
.find_map(|(key, &val)| if val == *max { Some(key) } else { None })
.unwrap()
}
有没有更好的方法或更优化的 std
方法来实现我想要的?或者说有一些社区制作的 Crate 可以使用。
BinaryHeap::into_sorted_vec()
可以避免重复弹出堆(这可能不是很好),或者您可以将 hashmap 收集到(count, item)
的 vec 中,然后按计数排序,并直接获取第 n 个元素。 - Masklinn