0347.前K个高频元素.md about rust

This commit is contained in:
fw_qaq
2022-10-31 17:48:33 +08:00
committed by GitHub
parent a4d54dd073
commit 31fa56d229

View File

@ -487,7 +487,34 @@ object Solution {
.map(_._1)
}
}
```
rust: 小根堆
```rust
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap};
impl Solution {
pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
let mut hash = HashMap::new();
let mut heap = BinaryHeap::with_capacity(k as usize);
nums.into_iter().for_each(|k| {
*hash.entry(k).or_insert(0) += 1;
});
for (k, v) in hash {
if heap.len() == heap.capacity() {
if *heap.peek().unwrap() < (Reverse(v), k) {
continue;
} else {
heap.pop();
}
}
heap.push((Reverse(v), k));
}
heap.into_iter().map(|(_, k)| k).collect()
}
}
```
<p align="center">