LeetCode 560. Subarray Sum Equals K

Problem Statement


use std::collections::HashMap;

impl Solution {
pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
let (mut ans, mut sum) = (0, 0);
let mut map = HashMap::new();
map.insert(0, 1);
for i in 0..nums.len() {
sum += nums[i];
map.entry(sum - k).or_insert(0);
ans += map[&(sum - k)];
map.entry(sum).or_insert(0);
*map.get_mut(&sum).unwrap() += 1;
}
return ans;
}
}