题目描述
https://leetcode-cn.com/problems/subarray-sum-equals-k/
解
func subarraySum(nums []int, k int) int {
if len(nums) == 0 {
return 0
}
// 计算当前值
var (
pre int
r int
// 哈希统计出现次数
s = make(map[int]int, len(nums)+1)
)
s[0] = 1
for _, v := range nums {
pre += v
if c, ok := s[pre-k]; ok {
r += c
}
s[pre]++
}
return r
}
思路
前缀+哈希,不过暴力可解!
网友评论