560.和为K 的子数组
https://leetcode-cn.com/problems/subarray-sum-equals-k/submissions/
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例:
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
解析:
1.暴力解:
也没有想出怎么暴力
2.借鉴两数之和的思想,hash表帮助解题,如果做出这个数组的累加和数组,那么这个问题就顺理成章地转化成 两数之差为K 的问题,迎刃而解。
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n = len(nums)
sums = {0:1}
result = 0
count = 0
for i in range(n):
result += nums[i]
if sums.has_key(result - k):
count += sums[result - k]
if sums.has_key(result):
sums[result] += 1
else:
sums[result] = 1
return count
3.知识点:
hash 表查找key的复杂度是O(1).
14,15行一定要放在16-19行前面,不然当K=0时,总是会搜到一个长度为0的子数组,就是自己这个位置。
第9行的初始化,代表从头开始的一个子数组。