【Leetcode】560. 和为K的子数组&974. 和可被 K 整除的子数组(前缀和+哈希表)
2024-08-30 06:46:46
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0, pre = 0;
HashMap < Integer, Integer > map = new HashMap < > ();
map.put(0, 1);
for (int i = 0; i < nums.length; i++) {
pre += nums[i];
if (mp.containsKey(pre - k))
count += mp.get(pre - k);
mp.put(pre, mp.getOrDefault(pre, 0) + 1);
}
return count;
}
}
class Solution {
public int subarraysDivByK(int[] A, int K) {
//记录余数出现的次数
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0,1);
int pre = 0;//前缀和
int ans = 0;
for(int i = 0; i < A.length; i++){
pre += A[i];
int m = (pre % K + K) % K;//余数 (负数处理)
int same = map.getOrDefault(m,0);
ans += same;
map.put(m,same+1);
}
return ans;
}
}
最新文章
- 【译】Getting Physical With Memory
- phpstorm 10注释的双斜线位置不在缩进的位置:
- 优化JS加载时间过长的一种思路
- session、cookie
- iOS开发流程总结
- Java EE开发平台随手记2——Mybatis扩展1
- iNeedle日志下载功能问题
- postgres 查询数据库所有表名
- python 变量命名规范
- 无法找到AdbWinApi.dll问题解决 .
- MySQL入门笔记
- Codeforces 552E - Vanya and Brackets【表达式求值】
- Android手势源码浅析-----手势绘制(GestureOverlayView)
- APP类别之比较与分析
- c# 操作word demo
- PyQt QFontDialog显示中文
- Nodejs(pkg方式安装)卸载 及命令行模式的重新安装
- 【bzoj 3306】树
- socketserver 实现并发
- J - Romantic