rustgym/leetcode/
_930_binary_subarrays_with_sum.rs1struct Solution;
2
3impl Solution {
4 fn num_subarrays_with_sum(a: Vec<i32>, s: i32) -> i32 {
5 let n = a.len();
6 let mut count = vec![0; n + 1];
7 count[0] = 1;
8 let mut sum = 0;
9 let mut res = 0;
10 for i in 0..n {
11 sum += a[i];
12 if sum >= s {
13 res += count[(sum - s) as usize];
14 }
15 count[sum as usize] += 1;
16 }
17 res as i32
18 }
19}
20
21#[test]
22fn test() {
23 let a = vec![1, 0, 1, 0, 1];
24 let s = 2;
25 let res = 4;
26 assert_eq!(Solution::num_subarrays_with_sum(a, s), res);
27}