diff --git "a/problems/0347.\345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240.md" "b/problems/0347.\345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240.md" index 4745645538..56dbaa33b3 100644 --- "a/problems/0347.\345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240.md" +++ "b/problems/0347.\345\211\215K\344\270\252\351\253\230\351\242\221\345\205\203\347\264\240.md" @@ -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, k: i32) -> Vec { + 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() + } +} ```