-
Notifications
You must be signed in to change notification settings - Fork 20
/
0347_top_k_frequent_elements.rs
84 lines (73 loc) · 2.14 KB
/
0347_top_k_frequent_elements.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! Given a non-empty array of integers, return the k most frequent elements.
//!
//! Example 1:
//!
//! Input: nums = [1,1,1,2,2,3], k = 2
//! Output: [1,2]
//!
//! Example 2:
//!
//! Input: nums = [1], k = 1
//! Output: [1]
//!
//! Note:
//!
//! + You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
//! + Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
//!
use std::collections::{BTreeMap, HashMap};
use std::option::Option::Some;
struct Solution;
impl Solution {
pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
let mut number_to_frequency_map: HashMap<i32, i32> = HashMap::new();
nums.iter().for_each(|i| {
*number_to_frequency_map.entry(*i).or_insert(0) += 1;
});
let mut frequency_to_numbers_map: BTreeMap<i32, Vec<i32>> = BTreeMap::new();
number_to_frequency_map.iter().for_each(|(key, value)| {
if let Some(old) = frequency_to_numbers_map.get_mut(value) {
old.insert(old.len(), *key);
} else {
frequency_to_numbers_map.insert(*value, vec![*key]);
}
});
let mut result: Vec<i32> = vec![];
for (_, value) in frequency_to_numbers_map.iter().rev() {
value.iter().for_each(|v| {
result.insert(result.len(), *v);
});
if (result.len() as i32) >= k {
break;
}
}
result
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use std::iter::FromIterator;
use super::Solution;
#[test]
fn test_0() {
assert_eq!(
BTreeSet::from_iter(Solution::top_k_frequent(vec![1, 1, 1, 2, 2, 3], 2)),
BTreeSet::from_iter(vec![1, 2])
);
}
#[test]
fn test_1() {
assert_eq!(
BTreeSet::from_iter(Solution::top_k_frequent(vec![1], 1)),
BTreeSet::from_iter(vec![1])
);
}
#[test]
fn test_2() {
assert_eq!(
BTreeSet::from_iter(Solution::top_k_frequent(vec![1, 2], 2)),
BTreeSet::from_iter(vec![1, 2])
);
}
}