和为k的子数组

给定一个整数数组和一个整数 k,你需要找到该数组中和为 的连续的子数组的个数。

示例 1 :

输入:nums = [1,1,1], k = 2

输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。

说明 :

  1. 数组的长度为 [1, 20,000]。
  2. 数组中元素的范围是 [-1000, 1000] ,且整数 的范围是 [-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;
}
}

最新文章

  1. webservice 测试窗体只能用于来自本地计算机的请求
  2. 算法:KMP算法
  3. android开发之线程
  4. Android界面性能调优手册
  5. TCP的那些事儿(下)
  6. C++编译器默默编写并调用哪些函数
  7. uva 10827
  8. Thread学习
  9. MVC-简单验证码制作
  10. HW5.8
  11. linux 文件内容的复制
  12. (转载)HDU4565
  13. 【leetcode】Single Number II
  14. Linux定时任务深入学习
  15. ELK学习总结(4-1)elasticsearch更改mapping(不停服务重建索引)
  16. Python获取会议部分的信息内容(不断完善中)
  17. Android AVD启动报错:emulator: ERROR: x86_64 emulation currently requires hardware acceleration! Please ensure Intel HAXM is properly installed and usable.
  18. 论文阅读:Review of Visual Saliency Detection with Comprehensive Information
  19. P3784 [SDOI2017]遗忘的集合
  20. Hive错误:Error: FUNCTION &#39;NUCLEUS_ASCII&#39; already exists. (state=X0Y68,code=30000)

热门文章

  1. A011 Activiti工作流程开发的一些统一规则和实现原理(完整版)
  2. 再回首win98
  3. PHP的模板引擎smarty原理浅谈
  4. windows xp professional 序列号(密钥)及百度网盘下载地址
  5. happy2018暑期集训课后习题001
  6. 在SAP云平台的CloudFoundry环境下消费ABAP On-Premise OData服务
  7. 手把手教你用Docker部署一个MongoDB集群
  8. [转]Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
  9. sublime package control以及常用插件
  10. React后台管理系统-用户列表页面