From 96d6b41260104563ab505c9156044034da01ec48 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Mon, 16 Dec 2024 22:12:17 +0800 Subject: [PATCH] Add problem 2364: Count Number of Bad Pairs --- src/lib.rs | 1 + .../iterative.rs | 51 +++++++++++++++++++ .../mod.rs | 18 +++++++ 3 files changed, 70 insertions(+) create mode 100644 src/problem_2364_count_number_of_bad_pairs/iterative.rs create mode 100644 src/problem_2364_count_number_of_bad_pairs/mod.rs diff --git a/src/lib.rs b/src/lib.rs index e90c8219..1d3768b8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1754,6 +1754,7 @@ pub mod problem_2357_make_array_zero_by_subtracting_equal_amounts; pub mod problem_2358_maximum_number_of_groups_entering_a_competition; pub mod problem_2360_longest_cycle_in_a_graph; pub mod problem_2363_merge_similar_items; +pub mod problem_2364_count_number_of_bad_pairs; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2364_count_number_of_bad_pairs/iterative.rs b/src/problem_2364_count_number_of_bad_pairs/iterative.rs new file mode 100644 index 00000000..7344353a --- /dev/null +++ b/src/problem_2364_count_number_of_bad_pairs/iterative.rs @@ -0,0 +1,51 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::collections::hash_map::Entry; +use std::collections::HashMap; + +impl Solution { + pub fn count_bad_pairs(nums: Vec) -> i64 { + let n = nums.len(); + let mut counts = HashMap::new(); + let mut good_pairs = 0; + + (0..).zip(nums).for_each(|(i, num)| { + let key = num - i; + + match counts.entry(key) { + Entry::Occupied(occupied_entry) => { + let count = occupied_entry.into_mut(); + + good_pairs += *count; + + *count += 1; + } + Entry::Vacant(vacant_entry) => { + vacant_entry.insert(1); + } + } + }); + + let n = n as u64; + + (n * (n - 1) / 2 - good_pairs) as _ + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn count_bad_pairs(nums: Vec) -> i64 { + Self::count_bad_pairs(nums) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2364_count_number_of_bad_pairs/mod.rs b/src/problem_2364_count_number_of_bad_pairs/mod.rs new file mode 100644 index 00000000..d52c8620 --- /dev/null +++ b/src/problem_2364_count_number_of_bad_pairs/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn count_bad_pairs(nums: Vec) -> i64; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [(&[4, 1, 3, 3] as &[_], 5), (&[1, 2, 3, 4, 5], 0)]; + + for (nums, expected) in test_cases { + assert_eq!(S::count_bad_pairs(nums.to_vec()), expected); + } + } +}