algorithm-base/animation-simulation/前缀和/leetcode523连续的子数组和.md

104 lines
5.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [523. ](https://leetcode-cn.com/problems/continuous-subarray-sum/)
****
> k 2 k n*k n
** 1**
> [23,2,4,6,7], k = 6
> True
[2,4] 2 6
** 2**
> [23,2,6,4,7], k = 6
> True
[23,2,6,4,7] 5 42
** + HashMap**
K 2
![_20210115174825](https://img-blog.csdnimg.cn/img_convert/953d09fbfffab9298152e143a39c85c0.png)
K = 6, presum % 6 = 4 [0,1] 2 [0,1]1 2 - 1 = 12 true[0,1],[0,2] presum % 6 = 4 1 2 1
![_20210115175122](https://img-blog.csdnimg.cn/img_convert/7bbd04ac578074d5fbccae7ab384f061.png)
2 [2,3] true
1 k 0 0 k 0 [0,0] , K = 0
2value 2 map.put(0,1) map.put(0,-1)[2,3,4],k = 1, map.put(0,-1) nums[1] 3 true 1--1= 25 % 1=0 ,
****
![](https://img-blog.csdnimg.cn/20210318094237943.gif#pic_center)
****
Java Code:
```java
class Solution {
public boolean checkSubarraySum(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<>();
//细节2
map.put(0,-1);
int presum = 0;
for (int i = 0; i < nums.length; ++i) {
presum += nums[i];
//细节1防止 k 为 0 的情况
int key = k == 0 ? presum : presum % k;
if (map.containsKey(key)) {
if (i - map.get(key) >= 2) {
return true;
}
//因为我们需要保存最小索引,当已经存在时则不用再次存入,不然会更新索引值
continue;
}
map.put(key,i);
}
return false;
}
}
```
C++ Code:
```cpp
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
map <int, int> m;
//细节2
m.insert({0,-1});
int presum = 0;
for (int i = 0; i < nums.size(); ++i) {
presum += nums[i];
//细节1防止 k 为 0 的情况
int key = k == 0 ? presum : presum % k;
if (m.find(key) != m.end()) {
if (i - m[key] >= 2) {
return true;
}
//因为我们需要保存最小索引,当已经存在时则不用再次存入,不然会更新索引值
continue;
}
m.insert({key, i});
}
return false;
}
};
```