From 31fa56d22947167a37ad767134ea98055314f367 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Mon, 31 Oct 2022 17:48:33 +0800 Subject: [PATCH] =?UTF-8?q?0347.=E5=89=8DK=E4=B8=AA=E9=AB=98=E9=A2=91?= =?UTF-8?q?=E5=85=83=E7=B4=A0.md=20about=20rust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 47456455..56dbaa33 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.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() + } +} ```