defsubarraySum(nums, k): length = len(nums) count = 0 for i in range(length): sum = 0 for j in range(i, length): sum += nums[j] if sum == k: count += 1 return count
defsubarraySum(self, nums, k): result, cur_sum = 0, 0 sum_dict = {0:1} for num in nums: cur_sum += num if cur_sum - k in sum_dict: result += sum_dict[cur_sum - k] sum_dict[cur_sum] = sum_dict.get(cur_sum, 0) + 1 return result
go实现的代码
funcsubarraySum(nums []int, k int)int { count := 0 sumMap := map[int]int{0:1,} sum := 0 for _, num := range nums { sum += num if sumMap[sum - k] > 0 { count += sumMap[sum - k] } sumMap[sum]++ }