Skip to content

Commit c5ded15

Browse files
author
lucifer
committed
feat: 更加容易理解
1 parent 83ffb18 commit c5ded15

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

problems/560.subarray-sum-equals-k.md

+11-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
## 题目地址(560. 和为K的子数组)
1+
## 题目地址(560. 和为 K 的子数组)
22

33
https://leetcode-cn.com/problems/subarray-sum-equals-k/
44

@@ -60,7 +60,16 @@ class Solution:
6060
return cnt
6161
```
6262

63-
这里有一种更加巧妙的方法,可以不使用前缀和数组,而是使用 hashmap 来简化时间复杂度,这种算法的时间复杂度可以达到 O(n).
63+
然而题目要求的仅仅是求**总数**,而不需要把所有的子数组求出。因此我们可直接使用下面的时间复杂度为 $O(n)$ 的算法。
64+
65+
这种做法的核心点在于, 题目让求的子数组总个数其实等价于:
66+
67+
- 以索引 0 结尾的子数组个数
68+
- 以索引 1 结尾的子数组个数
69+
- 。。。
70+
- 以索引 n - 1 结尾的子数组个数
71+
72+
而以索引 i 结尾的子数组个数等于:前缀和为 acc - k 的子数组个数,其中 acc 为当前的前缀和。为了能够快速取出前缀和为 acc - k 的个数,我们可将其存到哈希中。
6473

6574
具体算法:
6675

0 commit comments

Comments
 (0)