From 9725e1b05b4e314d84a42fe98dac456cc78ddb4a Mon Sep 17 00:00:00 2001 From: jackfiled Date: Thu, 7 Nov 2024 20:20:34 +0800 Subject: [PATCH] 20241107 finished. --- src/problem/mod.rs | 2 + ...5_find_the_power_of_k_size_subarrays_ii.rs | 60 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/problem/p3255_find_the_power_of_k_size_subarrays_ii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6dd665b..464d60a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -300,3 +300,5 @@ mod p633_sum_of_square_numbers; mod p3222_find_the_winning_player_in_coin_game; mod p3254_find_the_power_of_k_size_subarrays_i; + +mod p3255_find_the_power_of_k_size_subarrays_ii; diff --git a/src/problem/p3255_find_the_power_of_k_size_subarrays_ii.rs b/src/problem/p3255_find_the_power_of_k_size_subarrays_ii.rs new file mode 100644 index 0000000..b4238a0 --- /dev/null +++ b/src/problem/p3255_find_the_power_of_k_size_subarrays_ii.rs @@ -0,0 +1,60 @@ +/** + * [3255] Find the Power of K-Size Subarrays II + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn results_array(nums: Vec, k: i32) -> Vec { + let k = k as usize; + let n = nums.len(); + + let mut count = 0; + for i in 0..(k - 1) { + if nums[i] + 1 == nums[i + 1] { + count += 1; + } + } + + let mut result = Vec::with_capacity(n - k + 1); + result.push(if count == k - 1 { nums[k - 1] } else { -1 }); + + for i in k..n { + if nums[i - 1] + 1 == nums[i] { + count += 1; + } + + if nums[i - k] + 1 == nums[i - k + 1] { + count -= 1; + } + + result.push(if count == k - 1 { nums[i] } else { -1 }); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3255() { + assert_eq!( + vec![3, 4, -1, -1, -1], + Solution::results_array(vec![1, 2, 3, 4, 3, 2, 5], 3) + ); + assert_eq!( + vec![-1, -1], + Solution::results_array(vec![2, 2, 2, 2, 2], 4) + ); + assert_eq!( + vec![-1, 3, -1, 3, -1], + Solution::results_array(vec![3, 2, 3, 2, 3, 2], 2) + ); + } +}