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

104 lines
5.0 KiB
Java
Raw Normal View History

2021-03-20 11:38:55 +00:00
> **[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/)
2021-03-18 01:35:29 +00:00
****
> 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
2021-03-20 05:05:23 +00:00
![_20210115174825](https://img-blog.csdnimg.cn/img_convert/953d09fbfffab9298152e143a39c85c0.png)
2021-03-18 01:35:29 +00:00
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
2021-03-20 05:05:23 +00:00
![_20210115175122](https://img-blog.csdnimg.cn/img_convert/7bbd04ac578074d5fbccae7ab384f061.png)
2021-03-18 01:35:29 +00:00
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 ,
****
2021-03-18 01:44:45 +00:00
![](https://img-blog.csdnimg.cn/20210318094237943.gif#pic_center)
2021-03-18 01:35:29 +00:00
****
2021-04-27 07:11:05 +00:00
Java Code:
2021-03-18 01:35:29 +00:00
```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;
}
}
```
2021-04-27 07:11:05 +00:00
C++ Code:
2021-03-18 01:35:29 +00:00
2021-04-27 07:11:05 +00:00
```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;
}
};
```
2021-03-18 01:35:29 +00:00