Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1732 from Jack-Zhang-1314/patch-5
Browse files Browse the repository at this point in the history
0347.前K个高频元素.md about rust
  • Loading branch information
youngyangyang04 authored Nov 16, 2022
2 parents 6d75b12 + 31fa56d commit f8abd98
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions problems/0347.前K个高频元素.md
Original file line number Diff line number Diff line change
Expand Up @@ -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">
Expand Down

0 comments on commit f8abd98

Please sign in to comment.