rs: add «1481. Least Number of Unique Integers after K Removals»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
85d4d8d9ab
commit
57de9b067a
1 changed files with 49 additions and 0 deletions
49
rs/least-number-of-unique-integers-after-k-removals.rs
Normal file
49
rs/least-number-of-unique-integers-after-k-removals.rs
Normal 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
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue