Leetcode 560.和为k的子数组
2024-08-25 07:05:35
和为k的子数组
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
- 数组的长度为 [1, 20,000]。
- 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
思路
灵活使用map来解决问题
import java.util.HashMap;
import java.util.Map; class Solution {
public int subarraySum(int[] nums, int k) {
int sum = 0, result = 0;
Map<Integer, Integer> preSum = new HashMap<>();
preSum.put(0, 1); for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (preSum.containsKey(sum - k)) {
result += preSum.get(sum - k);
}
preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
} return result;
}
}
最新文章
- webservice 测试窗体只能用于来自本地计算机的请求
- 算法:KMP算法
- android开发之线程
- Android界面性能调优手册
- TCP的那些事儿(下)
- C++编译器默默编写并调用哪些函数
- uva 10827
- Thread学习
- MVC-简单验证码制作
- HW5.8
- linux 文件内容的复制
- (转载)HDU4565
- 【leetcode】Single Number II
- Linux定时任务深入学习
- ELK学习总结(4-1)elasticsearch更改mapping(不停服务重建索引)
- Python获取会议部分的信息内容(不断完善中)
- Android AVD启动报错:emulator: ERROR: x86_64 emulation currently requires hardware acceleration! Please ensure Intel HAXM is properly installed and usable.
- 论文阅读:Review of Visual Saliency Detection with Comprehensive Information
- P3784 [SDOI2017]遗忘的集合
- Hive错误:Error: FUNCTION &#39;NUCLEUS_ASCII&#39; already exists. (state=X0Y68,code=30000)
热门文章
- A011 Activiti工作流程开发的一些统一规则和实现原理(完整版)
- 再回首win98
- PHP的模板引擎smarty原理浅谈
- windows xp professional 序列号(密钥)及百度网盘下载地址
- happy2018暑期集训课后习题001
- 在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务
- 手把手教你用Docker部署一个MongoDB集群
- [转]Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
- sublime package control以及常用插件
- React后台管理系统-用户列表页面