20250416 finished.

This commit is contained in:
jackfiled 2025-04-16 11:26:07 +08:00
parent 5bf5b18f31
commit 4819b299c4
2 changed files with 60 additions and 0 deletions

View File

@ -601,3 +601,5 @@ mod p1922_count_good_numbers;
mod p1534_count_good_triplets; mod p1534_count_good_triplets;
mod p2179_count_good_triplets_in_an_array; mod p2179_count_good_triplets_in_an_array;
mod p2537_count_the_number_of_good_subarrays;

View File

@ -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<i32>, 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));
}
}