mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 09:59:41 +01:00
50 lines
1.1 KiB
Rust
50 lines
1.1 KiB
Rust
|
use std::collections::HashMap;
|
||
|
|
||
|
struct Solution {}
|
||
|
impl Solution {
|
||
|
pub fn find_least_num_of_unique_ints(arr: Vec<i32>, mut k: i32) -> i32 {
|
||
|
// count
|
||
|
let mut freqs: HashMap<i32, i32> = HashMap::new();
|
||
|
for &x in &arr {
|
||
|
*freqs.entry(x).or_insert(0) += 1;
|
||
|
}
|
||
|
|
||
|
// make a list of frequencies
|
||
|
let mut counts: Vec<(i32, i32)> = freqs.into_iter().collect();
|
||
|
counts.sort_by_key(|&(_, count)| count);
|
||
|
|
||
|
// count the rest after removing k
|
||
|
let mut unique = counts.len() as i32;
|
||
|
for &(_, count) in &counts {
|
||
|
if count <= k {
|
||
|
unique -= 1;
|
||
|
k -= count;
|
||
|
}
|
||
|
|
||
|
if k == 0 || count > k {
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
unique
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[cfg(test)]
|
||
|
mod tests {
|
||
|
use super::*;
|
||
|
|
||
|
#[test]
|
||
|
fn example_1() {
|
||
|
assert_eq!(Solution::find_least_num_of_unique_ints(vec![5, 5, 4], 1), 1);
|
||
|
}
|
||
|
|
||
|
#[test]
|
||
|
fn example_2() {
|
||
|
assert_eq!(
|
||
|
Solution::find_least_num_of_unique_ints(vec![4, 3, 1, 1, 3, 3, 2], 3),
|
||
|
2
|
||
|
);
|
||
|
}
|
||
|
}
|