From 4819b299c429ce0d42de81c529c1411cabf7ca47 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 16 Apr 2025 11:26:07 +0800 Subject: [PATCH] 20250416 finished. --- src/problem/mod.rs | 2 + ...2537_count_the_number_of_good_subarrays.rs | 58 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/problem/p2537_count_the_number_of_good_subarrays.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index a0d7c33..88e1fd6 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -601,3 +601,5 @@ mod p1922_count_good_numbers; mod p1534_count_good_triplets; mod p2179_count_good_triplets_in_an_array; + +mod p2537_count_the_number_of_good_subarrays; diff --git a/src/problem/p2537_count_the_number_of_good_subarrays.rs b/src/problem/p2537_count_the_number_of_good_subarrays.rs new file mode 100644 index 0000000..de19f69 --- /dev/null +++ b/src/problem/p2537_count_the_number_of_good_subarrays.rs @@ -0,0 +1,58 @@ +/** + * [2537] Count the Number of Good Subarrays + */ +pub struct Solution {} + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn count_good(nums: Vec, k: i32) -> i64 { + let mut map = HashMap::new(); + let n = nums.len(); + + let mut result = 0i64; + let mut count = 0; + let (mut left, mut right) = (0, 0); + + while left < n { + while right < n && count < k { + let entry = map.entry(nums[right]).or_insert(0); + count += *entry; + *entry += 1; + + right += 1; + } + + if count < k && right >= n { + // 拼尽全力无法战胜 + break; + } + + // 此时已经遇到了一个合格的序列 + // 注意序列可以多余的包含右侧的所有元素 + result += (n - right) as i64 + 1; + + // 右移left + let entry = map.entry(nums[left]).or_insert(0); + count -= *entry - 1; + *entry -= 1; + left += 1; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2537() { + assert_eq!(4, Solution::count_good(vec![3, 1, 4, 3, 2, 2, 4], 2)); + assert_eq!(1, Solution::count_good(vec![1, 1, 1, 1, 1], 10)); + } +}