1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00

rs: add «1481. Least Number of Unique Integers after K Removals»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-02-16 22:03:10 +01:00
parent 85d4d8d9ab
commit 57de9b067a
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,49 @@
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
);
}
}