Merge pull request #1732 from Jack-Zhang-1314/patch-5

0347.前K个高频元素.md about rust
This commit is contained in:
程序员Carl
2022-11-16 10:00:59 +08:00
committed by GitHub

View File

@ -487,7 +487,34 @@ object Solution {
.map(_._1) .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"> <p align="center">