We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 83ffb18 commit c5ded15Copy full SHA for c5ded15
problems/560.subarray-sum-equals-k.md
@@ -1,4 +1,4 @@
1
-## 题目地址(560. 和为K的子数组)
+## 题目地址(560. 和为 K 的子数组)
2
3
https://leetcode-cn.com/problems/subarray-sum-equals-k/
4
@@ -60,7 +60,16 @@ class Solution:
60
return cnt
61
```
62
63
-这里有一种更加巧妙的方法,可以不使用前缀和数组,而是使用 hashmap 来简化时间复杂度,这种算法的时间复杂度可以达到 O(n).
+然而题目要求的仅仅是求**总数**,而不需要把所有的子数组求出。因此我们可直接使用下面的时间复杂度为 $O(n)$ 的算法。
64
+
65
+这种做法的核心点在于, 题目让求的子数组总个数其实等价于:
66
67
+- 以索引 0 结尾的子数组个数
68
+- 以索引 1 结尾的子数组个数
69
+- 。。。
70
+- 以索引 n - 1 结尾的子数组个数
71
72
+而以索引 i 结尾的子数组个数等于:前缀和为 acc - k 的子数组个数,其中 acc 为当前的前缀和。为了能够快速取出前缀和为 acc - k 的个数,我们可将其存到哈希中。
73
74
具体算法:
75
0 commit comments