mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
rs: add «930. Binary Subarrays With Sum»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
8f865fa34c
commit
8717014c90
1 changed files with 34 additions and 0 deletions
34
rs/binary-subarrays-with-sum.rs
Normal file
34
rs/binary-subarrays-with-sum.rs
Normal file
|
@ -0,0 +1,34 @@
|
|||
impl Solution {
|
||||
pub fn num_subarrays_with_sum(nums: Vec<i32>, goal: i32) -> i32 {
|
||||
let mut subarrays = 0;
|
||||
|
||||
let mut sum = 0;
|
||||
let mut zeros = 0;
|
||||
|
||||
let mut l = 0;
|
||||
for r in 0..nums.len() {
|
||||
sum += nums[r];
|
||||
|
||||
while l < r && (nums[l] == 0 || sum > goal) {
|
||||
match nums[l] {
|
||||
0 => {
|
||||
zeros += 1;
|
||||
}
|
||||
1 => {
|
||||
zeros = 0;
|
||||
}
|
||||
_ => unreachable!("either 0 or 1s"),
|
||||
}
|
||||
|
||||
sum -= nums[l];
|
||||
l += 1;
|
||||
}
|
||||
|
||||
if sum == goal {
|
||||
subarrays += 1 + zeros;
|
||||
}
|
||||
}
|
||||
|
||||
subarrays
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue