Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. use std::cmp::Ordering;
  2. use std::collections::{BinaryHeap, HashMap};
  3.  
  4. pub struct Solution;
  5.  
  6. impl Solution {
  7. pub fn top_k_frequent(words: Vec<String>, k: i32) -> Vec<String> {
  8. let mut words_map = HashMap::new();
  9. let mut heap = BinaryHeap::new();
  10. for word in words {
  11. *words_map.entry(word).or_insert(0) += 1;
  12. }
  13. for (idx, entry) in words_map.into_iter().enumerate() {
  14. let word_count = WordCount::new(entry.0, entry.1);
  15. heap.push(word_count);
  16. if idx >= k as usize {
  17. heap.pop();
  18. }
  19. }
  20. heap.into_sorted_vec()
  21. .into_iter()
  22. .map(|word_count| word_count.word)
  23. .collect()
  24. }
  25. }
  26.  
  27. struct WordCount {
  28. word: String,
  29. count: i32,
  30. }
  31.  
  32. impl WordCount {
  33. fn new(word: String, count: i32) -> Self {
  34. WordCount { word, count }
  35. }
  36. }
  37.  
  38. impl PartialEq for WordCount {
  39. fn eq(&self, other: &Self) -> bool {
  40. self.count.eq(&other.count) && self.word.eq(&other.word)
  41. }
  42. }
  43.  
  44. impl Eq for WordCount {}
  45.  
  46. impl PartialOrd for WordCount {
  47. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
  48. Some(match other.count.cmp(&self.count) {
  49. Ordering::Equal => self.word.cmp(&other.word),
  50. order => order,
  51. })
  52. }
  53. }
  54.  
  55. impl Ord for WordCount {
  56. fn cmp(&self, other: &Self) -> Ordering {
  57. match other.count.cmp(&self.count) {
  58. Ordering::Equal => self.word.cmp(&other.word),
  59. order => order,
  60. }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement