From e843e149fa892c9e3067f2f35f08a41851ccd5de Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 15 Dec 2024 12:13:17 +0800 Subject: [PATCH] 20241215 finished. --- src/problem/mod.rs | 2 + .../p1338_reduce_array_size_to_the_half.rs | 54 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/problem/p1338_reduce_array_size_to_the_half.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 7b80f64..a71aa1a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -370,3 +370,5 @@ mod p2931_maximum_spending_after_buying_items; mod p3264_final_array_state_after_k_multiplication_operations_i; mod p3266_final_array_state_after_k_multiplication_operations_ii; + +mod p1338_reduce_array_size_to_the_half; diff --git a/src/problem/p1338_reduce_array_size_to_the_half.rs b/src/problem/p1338_reduce_array_size_to_the_half.rs new file mode 100644 index 0000000..b94b957 --- /dev/null +++ b/src/problem/p1338_reduce_array_size_to_the_half.rs @@ -0,0 +1,54 @@ +/** + * [1338] Reduce Array Size to The Half + */ +pub struct Solution {} + +// submission codes start here +use std::collections::BinaryHeap; +use std::collections::HashMap; + +impl Solution { + pub fn min_set_size(arr: Vec) -> i32 { + let mut map = HashMap::new(); + + for &i in arr.iter() { + let entry = map.entry(i).or_insert(0); + *entry += 1; + } + + let mut heap = BinaryHeap::with_capacity(map.len()); + + for (_, v) in map { + heap.push(v); + } + + let mut result = 0; + let mut count = arr.len(); + let target = count / 2; + + while count > target { + if let Some(head) = heap.pop() { + count -= head; + result += 1; + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1338() { + assert_eq!( + 2, + Solution::min_set_size(vec![3, 3, 3, 3, 5, 5, 5, 2, 2, 7]) + ); + assert_eq!(1, Solution::min_set_size(vec![7, 7, 7, 7, 7, 7])); + } +}