062_和为K的子数组
知识点:前缀和、哈希表
LeetCode第五百六十题:https://leetcode-cn.com/problems/subarray-sum-equals-k/submissions/
语言:GoLang
// 前缀和 + 哈希表
func subarraySum(nums []int, k int) int {
length := len(nums)
hMap, preSum, count := map[int]int{0: 1}, 0, 0
for i := 1; i <= length; i++ {
preSum = nums[i - 1] + preSum
if value, ok := hMap[preSum - k]; ok {
count += value
}
hMap[preSum]++
}
return count
}
// 朴素解法,O(n^2)
func subarraySum_0(nums []int, k int) int {
length := len(nums)
count := 0
for i := 0; i < length; i++ {
sum := 0
for j := i; j < length; j++ {
sum += nums[j]
if sum == k {
count++
}
}
}
return count
}