当前位置:网站首页>560 和为 K 的子数组
560 和为 K 的子数组
2022-07-29 00:40:00 【爪哇贡尘拾Miraitow】
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的连续子数组的个数 。
前缀和:nums 的第 0 项到 当前项 的和。
定义 prefixSum 数组,prefixSum[x]:第 0 项到 第 x 项 的和。
- prefixSum[x] = nums[0] + nums[1] +…+nums[x]
- prefixSum[x]=nums[0]+nums[1]+…+nums[x]
nums 的某项 = 两个相邻前缀和的差:
- nums[x] = prefixSum[x] - prefixSum[x - 1]
- nums[x]=prefixSum[x]−prefixSum[x−1]
nums 的 第 i 到 j 项 的和,有:
- nums[i] +…+nums[j]=prefixSum[j] - prefixSum[i - 1]
- nums[i]+…+nums[j]=prefixSum[j]−prefixSum[i−1]
当 i 为 0,此时 i-1 为 -1,我们故意让 prefixSum[-1] 为 0,使得通式在i=0时也成立:
- nums[0] +…+nums[j]=prefixSum[j]
- nums[0]+…+nums[j]=prefixSum[j]
题目的等价转化
不用求出 prefixSum 数组
其实我们不关心具体是哪两项的前缀和之差等于k,只关心等于 k 的前缀和之差出现的次数c,就知道了有c个子数组求和等于k。
遍历 nums 之前,我们让 -1 对应的前缀和为 0,这样通式在边界情况也成立。即在遍历之前,map 初始放入 0:1 键值对(前缀和为0出现1次了)。
遍历 nums 数组,求每一项的前缀和,统计对应的出现次数,以键值对存入 map。
边存边查看 map,如果 map 中存在 key 为「当前前缀和 - k」,说明这个之前出现的前缀和,满足「当前前缀和 - 该前缀和 == k」,它出现的次数,累加给 count。
代码
时间复杂度 O(n) 。空间复杂度 O(n)
class Solution {
public int subarraySum(int[] nums, int k) {
int pre = 0, count = 0;
Map<Integer,Integer> map = new HashMap<>();
map.put(0,1);
for( int i=0;i<nums.length;i++){
pre += nums[i];
if(map.containsKey(pre-k)){
count += map.get(pre-k);
}
map.put(pre,map.getOrDefault(pre,0)+1);
}
return count;
}
}
边栏推荐
- Teach you a text to solve the problem of JS digital accuracy loss
- Common functions and usage of numpy
- Flink SQL Hudi 实战
- Linux Redis 源码安装
- Flask generates image verification code
- Intel introduces you to visual recognition -- openvino
- Numpy 常见函数及使用
- 梅克尔工作室——HarmonyOS实现列表待办
- Regular checksum time formatting
- 如何选择专业、安全、高性能的远程控制软件
猜你喜欢

了解各种路径

Oozie工作调度

PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益

表达式求值

【idea】查询字段使用位置

PlatoFarm社区生态福音,用户可借助Elephant Swap获得溢价收益

Error reporting: SQL syntax error in flask. Fields in SQL statements need quotation marks when formatting

20220728 sorting strings that are not pure numbers

Openpyxl border

After understanding the composition of the URL of the website, we use the URL module, querystring module and mime module to improve the static website
随机推荐
MySQL time is formatted by hour_ MySQL time format, MySQL statement queried by time period [easy to understand]
Use of resttemplate and Eureka
Flink Postgres CDC
Flink Postgres CDC
Flash reports an error: type object 'news' has no attribute' query 'the view name is duplicate with the model name
Naver 三方登录
Canal real-time parsing MySQL binlog data practice
matplotlib中文问题
SQL question brushing: find the last of all employees who have been assigned departments_ Name and first_ Name and Dept_ no
PlatoFarm社区生态福音,用户可借助Elephant Swap获得溢价收益
全新升级:获得淘宝商品详情“高级版” API
App access kakaotalk three party login
Self-attention neural architecture search for semantic image segmentation
【SQL之降龙十八掌】01——亢龙有悔:入门10题
els 新的方块落下
Bracket matching test
Naver three party login
18 diagrams, intuitive understanding of neural networks, manifolds and topologies
Numpy 常见函数及使用
【ManageEngine】局域网监控软件是什么,有什么作用