algorithm-base/animation-simulation/前缀和/leetcode974和可被K整除的子数组.md

135 lines
5.2 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>进入。
#### [974. K ](https://leetcode-cn.com/problems/subarray-sums-divisible-by-k/)
****
> A K
****
> A = [4,5,0,-2,-3,1], K = 5
> 7
****
> 7 K = 5
> [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
**+HashMap**
****
**K **
![_20210115194113](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210115194113.5e56re9qdic0.png)
K presum k presum - k k
![_20210115150520](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210115150520.3kh5yiwwmlm0.png)
presum[j+1] - presum[i] nums[i] + nums[i+1]+.... nums[j][i,j]
[i,j] K K
(presum[j+1] - presum[i] ) % k 0
(presum[j+1] - presum[i] ) % k == 0
presum[j+1] % k - presum[i] % k == 0;
presum[j +1] % k = presum[i] % k ;
presum[j +1] % k key presum k key K
![_20210115152113](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210115152113.606bcpexpww0.png)
****
```java
class Solution {
public int subarraysDivByK(int[] A, int K) {
HashMap<Integer,Integer> map = new HashMap<>();
map.put(0,1);
int presum = 0;
int count = 0;
for (int x : A) {
presum += x;
//当前 presum 与 K的关系余数是几当被除数为负数时取模结果为负数需要纠正
int key = (presum % K + K) % K;
//查询哈希表获取之前key也就是余数的次数
if (map.containsKey(key)) {
count += map.get(key);
}
//存入哈希表当前key也就是余数
map.put(key,map.getOrDefault(key,0)+1);
}
return count;
}
}
```
```java
int key = (presum % K + K) % K;
```
presum % k
presum (-1) %2 = (-1) ( (-1) % 2 + 2) % 2=1 1. [-1,2,9],K = 2 [2] 2 % 2 = 0
map K-1 K
Java Code:
```java
class Solution {
public int subarraysDivByK(int[] A, int K) {
int[] map = new int[K];
map[0] = 1;
int len = A.length;
int presum = 0;
int count = 0;
for (int i = 0; i < len; ++i) {
presum += A[i];
//求key
int key = (presum % K + K) % K;
//count添加次数并将当前的map[key]++;
count += map[key]++;
}
return count;
}
}
```
C++ Code:
```cpp
class Solution {
public:
int subarraysDivByK(vector<int>& A, int K) {
vector <int> map (K, 0);
int len = A.size();
int count = 0;
int presum = 0;
map[0] = 1;
for (int i = 0; i < len; ++i) {
presum += A[i];
//求key
int key = (presum % K + K) % K;
//count添加次数并将当前的map[key]++;
count += (map[key]++);
}
return count;
}
};
```