diff --git a/solution/2800-2899/2845.Count of Interesting Subarrays/README.md b/solution/2800-2899/2845.Count of Interesting Subarrays/README.md index 0935acfe76c62..812f37098d38b 100644 --- a/solution/2800-2899/2845.Count of Interesting Subarrays/README.md +++ b/solution/2800-2899/2845.Count of Interesting Subarrays/README.md @@ -208,6 +208,35 @@ function countInterestingSubarrays(nums: number[], modulo: number, k: number): n } ``` +#### Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn count_interesting_subarrays(nums: Vec, modulo: i32, k: i32) -> i64 { + let mut arr: Vec = nums + .iter() + .map(|&x| if x % modulo == k { 1 } else { 0 }) + .collect(); + let mut cnt: HashMap = HashMap::new(); + cnt.insert(0, 1); + + let mut ans: i64 = 0; + let mut s: i32 = 0; + + for x in arr { + s += x; + let key = (s - k).rem_euclid(modulo); + ans += *cnt.get(&key).unwrap_or(&0); + *cnt.entry(s % modulo).or_insert(0) += 1; + } + + ans + } +} +``` + diff --git a/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md b/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md index 043784d59ce20..49fb57a6e472c 100644 --- a/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md +++ b/solution/2800-2899/2845.Count of Interesting Subarrays/README_EN.md @@ -206,6 +206,35 @@ function countInterestingSubarrays(nums: number[], modulo: number, k: number): n } ``` +#### Rust + +```rust +use std::collections::HashMap; + +impl Solution { + pub fn count_interesting_subarrays(nums: Vec, modulo: i32, k: i32) -> i64 { + let mut arr: Vec = nums + .iter() + .map(|&x| if x % modulo == k { 1 } else { 0 }) + .collect(); + let mut cnt: HashMap = HashMap::new(); + cnt.insert(0, 1); + + let mut ans: i64 = 0; + let mut s: i32 = 0; + + for x in arr { + s += x; + let key = (s - k).rem_euclid(modulo); + ans += *cnt.get(&key).unwrap_or(&0); + *cnt.entry(s % modulo).or_insert(0) += 1; + } + + ans + } +} +``` + diff --git a/solution/2800-2899/2845.Count of Interesting Subarrays/Solution.rs b/solution/2800-2899/2845.Count of Interesting Subarrays/Solution.rs new file mode 100644 index 0000000000000..7658bea9e79ef --- /dev/null +++ b/solution/2800-2899/2845.Count of Interesting Subarrays/Solution.rs @@ -0,0 +1,24 @@ +use std::collections::HashMap; + +impl Solution { + pub fn count_interesting_subarrays(nums: Vec, modulo: i32, k: i32) -> i64 { + let mut arr: Vec = nums + .iter() + .map(|&x| if x % modulo == k { 1 } else { 0 }) + .collect(); + let mut cnt: HashMap = HashMap::new(); + cnt.insert(0, 1); + + let mut ans: i64 = 0; + let mut s: i32 = 0; + + for x in arr { + s += x; + let key = (s - k).rem_euclid(modulo); + ans += *cnt.get(&key).unwrap_or(&0); + *cnt.entry(s % modulo).or_insert(0) += 1; + } + + ans + } +}