This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

0550-0599

Solutions to LeetCode Problems 0550-0599.

1 - 0560.和为 K 的子数组

方法一:前缀和数组

时间复杂度 $O(n)$,空间复杂度 $O(n)$。

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