LeetCode-in-All

560. Subarray Sum Equals K

Medium

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,1,1], k = 2

Output: 2

Example 2:

Input: nums = [1,2,3], k = 3

Output: 2

Constraints:

Solution

use std::collections::HashMap;

impl Solution {
    pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
        let mut temp_sum = 0;
        let mut ret = 0;
        let mut sum_count: HashMap<i32, i32> = HashMap::new();
        sum_count.insert(0, 1);
        
        for &num in nums.iter() {
            temp_sum += num;
            if let Some(&count) = sum_count.get(&(temp_sum - k)) {
                ret += count;
            }
            let entry = sum_count.entry(temp_sum).or_insert(0);
            *entry += 1;
        }
        
        ret
    }
}