-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0560_subarray_sum_equals_k.rs
More file actions
40 lines (33 loc) · 968 Bytes
/
s0560_subarray_sum_equals_k.rs
File metadata and controls
40 lines (33 loc) · 968 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#![allow(unused)]
pub struct Solution {}
impl Solution {
pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
use std::collections::HashMap;
let mut map = HashMap::new();
let mut count = 0;
let mut cursum = 0;
for &num in nums.iter() {
// current prefix sum
cursum += num;
// case 1
// continuous subarray starts
// from the beginning of the array
if cursum == k {
count += 1;
}
// case 2
// number of times the curr_sum − k has occured already,
// determines the number of times a subarray with sum k
// has occured upto the current index
count += map.get(&(cursum - k)).cloned().unwrap_or(0);
*map.entry(cursum).or_insert(0) += 1;
}
count
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_560() {}
}