aboutsummaryrefslogtreecommitdiff
path: root/other/top_k_freq_words.rs
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/top_k_freq_words.rs
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/top_k_freq_words.rs')
-rw-r--r--other/top_k_freq_words.rs26
1 files changed, 26 insertions, 0 deletions
diff --git a/other/top_k_freq_words.rs b/other/top_k_freq_words.rs
new file mode 100644
index 0000000..606c237
--- /dev/null
+++ b/other/top_k_freq_words.rs
@@ -0,0 +1,26 @@
+use std::collections::BinaryHeap;
+use std::collections::HashMap;
+
+struct Solution;
+
+impl Solution {
+ pub fn top_k_frequent(words: Vec<String>, k: i32) -> Vec<String> {
+ let mut word_to_freq = HashMap::<String, i32>::new();
+ for w in words {
+ *word_to_freq.entry(w).or_default() += 1;
+ }
+ let mut heap = BinaryHeap::<(i32, String)>::new();
+ for (word, freq) in word_to_freq {
+ heap.push((-freq, word));
+ if heap.len() > k as usize {
+ heap.pop();
+ }
+ }
+ let mut ans: Vec<String> = vec![];
+ while let Some((_freq, word)) = heap.pop() {
+ ans.push(word);
+ }
+ ans.reverse();
+ ans
+ }
+}