当前位置:网站首页>Clearance sword refers to Offer——The sword refers to Offer II 010. and the sub-array of k
Clearance sword refers to Offer——The sword refers to Offer II 010. and the sub-array of k
2022-08-04 17:03:00 【SK_Jaco】
1.题目描述
给定一个整数数组和一个整数 k ,请找到该数组中和为 k 的连续子数组的个数.
示例 1:
输入:nums = [1,1,1], k = 2
输出: 2
解释: 此题 [1,1] 与 [1,1] 为两种不同的情况
示例 2:
输入:nums = [1,2,3], k = 3
输出: 2
2.解题思路与代码
2.1 解题思路
This problem requires summing up contiguous subarrays of a number,Then the problem of summing continuous subarrays like this can first be solved by using prefix sum.We denote prefixes and arrays as sum[] The original array is recorded as num[],Prefixes and arrays have the following two properties
- 前缀和数组第 i The bit value is the original array [0, i] The sum of all elements in bits
- sum[i]-sum[j] (i>j) equal to the original array [i+1, j] 上元素之和
基于这两个特性,We can know the contiguous subarray sum required by the title k,In fact, it is to find whether there are two positions on the prefix and the array i 和 j (其中 j>i)使得 sum[j]-sum[i]=k,After this is deduced, the problem is very simple.
We have the above formula sum[j]-sum[i]=k 进行变形得到 sum[j]-k=sum[i],When we get the prefix and the array, we traverse the original array from the beginning to the end num[],And the meaning of this deformed formula is when we find the first j The prefix and hour of the location,在 j Whether there is a prefix and equals to the first j Prefix and subtract of positions k,每存在一个 sum[i] 等于 sum[j]-k Add the statistics 1.由于需要在 j Look up the prefix sum before,To reduce traversal we use a hash table to store the number of prefixes and counts previously computed.这里有一点需要注意,The prefix sum array requires one more bit than the original array,And the prefix sums the first of the array 0 位置为 0.
以题目示例 nums = [1,1,1], k = 2 为例进行图解.
First we initialize the prefix sum array and hash table,The prefix and array bits are one more than the original array to store the initial 0,Indicates that the prefix sum is yes when no number is selected at this time 0,并将 0 放入哈希表中
Start calculating the prefix sum,Traverse the first position of the original array,此时 sum[1] 等于 1,Then according to the previous formula,We need to find the first 1 Whether there is a prefix and equals in front of the bitsum[1]-k 即 -1,It was not found in the hash table,于是将 sum[1] Continue to traverse after putting into the hash table
Continue to calculate the prefix sum,此时 sum[2] 等于 2,Then need to see sum[2] Whether there is a prefix and equals before sum[2]-2 即 0,can be obtained from the hash table 0 出现了一次,统计结果加一,并将 sum[2] 放入哈希表中
Finally traverse to the first of the original array 2 位,此时 sum[3] 等于 3,Then you need to find whether it exists in the previous prefix sum sum[3]-2 即 1,在哈希表中存在 1,and only appeared once,So the result is incremented by one,最终得到结果是 2.
2.2 代码
class Solution {
public int subarraySum(int[] nums, int k) {
if (nums.length == 1) {
return nums[0] == k ? 1 : 0;
}
// 初始化前缀和数组,The length is one bit more than the original array,并且第 0 位设置为 0
int[] sum = new int[nums.length + 1];
sum[0] = 0;
// Initialize the hash table storage
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int ans = 0;
for (int i = 1; i < nums.length + 1; i++) {
// 计算前缀和,and calculate what needs to be looked up target
sum[i] = sum[i - 1] + nums[i - 1];
int target = sum[i] - k;
// Read from hash table target included in the results
ans += map.getOrDefault(target, 0);
// Store the prefix sum of the current bit into the hash table
map.put(sum[i], map.getOrDefault(sum[i], 0) + 1);
}
return ans;
}
}
2.3 测试结果
通过测试
3.总结
- Solve using prefix sum and hash table
- Prefixes and arrays need to be initialized to use 0 占位
边栏推荐
猜你喜欢
随机推荐
Boost库学习笔记(一)安装与配置
R语言使用yardstick包的gain_curve函数评估多分类(Multiclass)模型的性能、查看模型在多分类每个分类上的增益(gain)曲线(gain curve)
力拓信创生态,博睿数据多款产品获得东方通与达梦数据库产品兼容互认证明
乐享购(分享购)的模式:优势、亮点、收益
WEB 渗透之逻辑漏洞
response的contentType 几种类型
机器学习(十六):主成成分分析(PCA)
北京海淀6家必胜客被暂停外卖订餐 存在食品安全问题
R语言使用cov函数计算矩阵或者dataframe数据变量之间的协方差、cor函数计算相关性、cor函数通过method参数指定相关性、相关性计算方法Pearson,Spearman, Kendall
泰坦尼克号沉船数据之美——起于悲剧,止于浪漫
redis
抖音最重要的接口——item_search_video-根据关键词获取视频列表
SRM供应商协同管理系统功能介绍
跨链桥已成行业最大安全隐患 为什么和怎么办
水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...
Minecraft 服务器安装Forge 并添加Mod
SAP 电商云 Spartacus UI SSR 单元测试里的 callFake
湖北电信天邑TY1608_S905L3B_MT7668_卡刷固件包
适配器模式
麒麟信安石勇博士荣获openEuler社区年度开源贡献之星








