当前位置:网站首页>High frequency interview questions -- subarray with sum K
High frequency interview questions -- subarray with sum K
2022-07-18 13:29:00 【Doghead Intern】
The finger of the sword Offer II 010. And for k Subarray
Given an array of integers and an integer k , Please find the array with k The number of consecutive subarrays of .
Example 1:
Input :nums = [1,1,1], k = 2
Output : 2
explain : This question [1,1] And [1,1] For two different situations
Example 2:
Input :nums = [1,2,3], k = 3
Output : 2
Tips :
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
Ideas
Array :0…i…j…end
When we want to judge j Whether there are conditions for the number , We just need to judge j The number minus 0 To i The number and (0<i<j) Is it equal to k You can judge whether there are conditions ( Section i+1 To j And ).
So let's just go ahead i Record the sum of the numbers , As a prefix , Then use the one with relatively high efficiency hashmap Record prefix , You can quickly find the answer .
class Solution {
public int subarraySum(int[] nums, int k) {
HashMap<Integer,Integer> map = new HashMap<>();
int pre = 0,count = 0;
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);
}
// Judge whether it exists per key , If exist , Then take pre value +1, If it does not exist , Then create a , The value is 0
map.put(pre,map.getOrDefault(pre,0)+1);
}
return count;
}
}
The code is the official answer , Record your understanding here
边栏推荐
猜你喜欢
随机推荐
How to solve pycharm's inability to input Chinese:
三匹马携手乾元公益基金会 | 炎夏送清凉,致敬坚守者 !
Work method record
打工人打工魂!销售分析案例来啦!
Yiwen xuxue pyspark data analysis foundation: Spark local environment deployment and construction
剑指 Offer 27. 二叉树的镜像
【机器学习 - 决策树】信息增益
[notes] cryptography from introduction to earth | AES
ClickHouse(04)如何搭建ClickHouse集群
Template_ Euclidean sieve_ prime number
Kingbasees SQL language reference manual of Jincang database (3.1.1.9. network address type)
剑指 Offer 26. 树的子结构
剑指 Offer 46. 把数字翻译成字符串
Use PSSH to execute commands on multiple hosts in batches
【机器学习】在线学习 - Online Learning
What is the ECS framework? Explain + practice to get you started ECS framework
An understanding of mapstruct domain transformation tool!
Summary of various parameters of ultra micro motherboard
28K monthly salary for software testing interview questions for large factories (you can take away the test paper with the permission of the interviewer)
OpenCV、EmguCV和OpenCvSharp指针访问图像像素值耗时测评(附源码)


![[notes] overview of cryptography from introduction to earth](/img/b5/264ebc3a812460e97d7385d229ac72.png)




![[machine learning] decision tree](/img/ae/7dac0bddc7f55ecabe49ab5ef4b429.png)
