From bbb8aec61ebca24b034d8868d9d4383a086a08e5 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 6 Nov 2024 11:51:01 +0800 Subject: [PATCH] 20241106 finished. --- src/problem/mod.rs | 2 + ...54_find_the_power_of_k_size_subarrays_i.rs | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/problem/p3254_find_the_power_of_k_size_subarrays_i.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4ca4c2e..6dd665b 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -298,3 +298,5 @@ mod p638_shopping_offers; 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; diff --git a/src/problem/p3254_find_the_power_of_k_size_subarrays_i.rs b/src/problem/p3254_find_the_power_of_k_size_subarrays_i.rs new file mode 100644 index 0000000..258427c --- /dev/null +++ b/src/problem/p3254_find_the_power_of_k_size_subarrays_i.rs @@ -0,0 +1,61 @@ +/** + * [3254] Find the Power of K-Size Subarrays I + */ +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_3254() { + assert_eq!(vec![1, 2, 3], Solution::results_array(vec![1, 2, 3], 1)); + 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) + ); + } +}