vault backup: 2022-09-05 16:41:34
This commit is contained in:
parent
e3bff4cb79
commit
f18afcaa6a
|
@ -16,7 +16,7 @@
|
|||
>
|
||||
> ##### Additional tags:
|
||||
>
|
||||
> #leetcode
|
||||
> #leetcode #CS_list_need_practicing
|
||||
>
|
||||
> ##### Revisions:
|
||||
>
|
||||
|
@ -25,6 +25,7 @@
|
|||
##### Links:
|
||||
|
||||
- [Link to problem](https://leetcode.com/problems/subarray-sum-equals-k/)
|
||||
- [Explanation](https://leetcode.com/problems/subarray-sum-equals-k/discuss/102111/Python-Simple-with-Explanation/694092)
|
||||
|
||||
---
|
||||
|
||||
|
@ -64,10 +65,50 @@ A subarray is a contiguous **non-empty** sequence of elements within an array.
|
|||
> Tried using sliding window, but it doesn't work because of
|
||||
> negative numbers.
|
||||
|
||||
This one is harder to understand, making it a medium
|
||||
difficulty problem.
|
||||
|
||||
The intuition is using prefix to count the subarray sum, and
|
||||
use hashmaps to count the **number of subarray sums**. This
|
||||
takes care of **negative numbers** which is not solvable
|
||||
using sliding windows.
|
||||
|
||||
We step one cell at a time, and try to ask ourselves:
|
||||
`Can we hop back K to land on a cell?`
|
||||
|
||||
And we answer this question by using hash maps and recording
|
||||
the data on the fly.
|
||||
|
||||
### Solution
|
||||
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
int subarraySum(vector<int> &nums, int k) {
|
||||
unordered_map<int, int> umap;
|
||||
// sum == k is a solution, should be counted
|
||||
umap[0] = 1;
|
||||
|
||||
int sum = 0;
|
||||
int count = 0;
|
||||
|
||||
for (int i : nums) {
|
||||
// update the prefix sum
|
||||
sum += i;
|
||||
|
||||
if (umap.find(sum - k) != umap.end()) {
|
||||
// we can land on a cell, then add the counter.
|
||||
count += umap[sum - k];
|
||||
}
|
||||
|
||||
// record this step.
|
||||
umap[sum]++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
TLE, brute force
|
||||
```cpp
|
||||
|
|
Loading…
Reference in a new issue