返回介绍

solution / 0500-0599 / 0560.Subarray Sum Equals K / README_EN

发布于 2024-06-17 01:03:59 字数 3764 浏览 0 评论 0 收藏 0

560. Subarray Sum Equals K

中文文档

Description

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:

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -107 <= k <= 107

Solutions

Solution 1

class Solution:
  def subarraySum(self, nums: List[int], k: int) -> int:
    counter = Counter({0: 1})
    ans = s = 0
    for num in nums:
      s += num
      ans += counter[s - k]
      counter[s] += 1
    return ans
class Solution {
  public int subarraySum(int[] nums, int k) {
    Map<Integer, Integer> counter = new HashMap<>();
    counter.put(0, 1);
    int ans = 0, s = 0;
    for (int num : nums) {
      s += num;
      ans += counter.getOrDefault(s - k, 0);
      counter.put(s, counter.getOrDefault(s, 0) + 1);
    }
    return ans;
  }
}
class Solution {
public:
  int subarraySum(vector<int>& nums, int k) {
    unordered_map<int, int> counter;
    counter[0] = 1;
    int ans = 0, s = 0;
    for (int& num : nums) {
      s += num;
      ans += counter[s - k];
      ++counter[s];
    }
    return ans;
  }
};
func subarraySum(nums []int, k int) int {
  counter := map[int]int{0: 1}
  ans, s := 0, 0
  for _, num := range nums {
    s += num
    ans += counter[s-k]
    counter[s]++
  }
  return ans
}
function subarraySum(nums: number[], k: number): number {
  let ans = 0,
    s = 0;
  const counter = new Map();
  counter.set(0, 1);
  for (const num of nums) {
    s += num;
    ans += counter.get(s - k) || 0;
    counter.set(s, (counter.get(s) || 0) + 1);
  }
  return ans;
}
impl Solution {
  pub fn subarray_sum(mut nums: Vec<i32>, k: i32) -> i32 {
    let n = nums.len();
    let mut count = 0;
    for i in 0..n {
      let num = nums[i];
      if num == k {
        count += 1;
      }
      for j in 0..i {
        nums[j] += num;
        if nums[j] == k {
          count += 1;
        }
      }
    }
    count
  }
}

Solution 2

use std::collections::HashMap;

impl Solution {
  pub fn subarray_sum(nums: Vec<i32>, k: i32) -> i32 {
    let mut res = 0;
    let mut sum = 0;
    let mut map = HashMap::new();
    map.insert(0, 1);
    nums.iter().for_each(|num| {
      sum += num;
      res += map.get(&(sum - k)).unwrap_or(&0);
      map.insert(sum, map.get(&sum).unwrap_or(&0) + 1);
    });
    res
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文