版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuxuemingzhu/article/details/82767119
【LeetCode】560. Subarray Sum Equals K 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/subarray-sum-equals-k/description/
题目描述:
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
题目大意
求数组中有多少个连续子数组的和正好等于k。
解题方法
看了数组的长度,明显O(n^2)的时间复杂度会超时。这个时间复杂度一般只能用O(N)的解法了。
使用一个字典保存数组某个位置之前的数组和,然后遍历数组求和,这样当我们求到一个位置的和的时候,向前找sum-k是否在数组中,如果在的话,更新结果为之前的结果+1。同时,当前这个sum出现的次数就多了一次。
这个题的解法不难想出来,因为如果要降低时间复杂度,应该能想到增加空间复杂度,那么要么使用数组,要么就是用字典之类的,保留之前的结果。
时间复杂度是O(N),空间复杂度是O(N).
代码如下:
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
n = len(nums)
d = collections.defaultdict(int)
d[0] = 1
sum = 0
res = 0
for i in range(n):
sum += nums[i]
if sum - k in d:
res += d[sum - k]
d[sum] += 1
return res
参考资料:
https://leetcode.com/submissions/detail/176956930/
日期
2018 年 9 月 19 日 —— 梦见李彦宏和我聊微信,他感谢我给一个短视频App做了分享功能……