add: 和可被K整除的子数组
This commit is contained in:
1 parent
6098f48863
commit
596ae26ade
13 files changed
+26
No files matched your search
@@ -353,6 +353,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
|||||||
- LeetCode 287. 寻找重复数 <https://leetcode-cn.com/problems/find-the-duplicate-number/>
|
- LeetCode 287. 寻找重复数 <https://leetcode-cn.com/problems/find-the-duplicate-number/>
|
||||||
- LintCode 633. 寻找重复的数 <https://www.lintcode.com/problem/find-the-duplicate-number/description>
|
- LintCode 633. 寻找重复的数 <https://www.lintcode.com/problem/find-the-duplicate-number/description>
|
||||||
|
|
||||||
|
- [和可被K整除的子数组](src/array/subarray-sums-divisible-by-k.js)
|
||||||
|
|
||||||
|
- LeetCode 974. 和可被 K 整除的子数组 <https://leetcode-cn.com/problems/subarray-sums-divisible-by-k/>
|
||||||
|
|
||||||
## 栈
|
## 栈
|
||||||
|
|
||||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* @param {number[]} A
|
||||||
|
* @param {number} K
|
||||||
|
* @return {number}
|
||||||
|
*/
|
||||||
|
export const subarraysDivByK = function (A, K) {
|
||||||
|
const map = new Map([[0, 1]]); let sum = 0; let count = 0
|
||||||
|
|
||||||
|
A.forEach(n => {
|
||||||
|
sum = (sum + n) % K; sum = sum < 0 ? sum + K : sum
|
||||||
|
const temp = map.get(sum) || 0
|
||||||
|
count += temp
|
||||||
|
map.set(sum, temp + 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
return count
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,5 @@
|
|||||||
|
import { subarraysDivByK } from '../../src/array/subarray-sums-divisible-by-k'
|
||||||
|
|
||||||
|
test('和可被K整除的子数组', () => {
|
||||||
|
expect(subarraysDivByK([4, 5, 0, -2, -3, 1], 5)).toBe(7)
|
||||||
|
})
|
||||||
Reference in new issue
Block a user