当前位置:网站首页>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 占位
边栏推荐
猜你喜欢
Minecraft 我的世界 .minecraft下的各个文件夹的用处
shell脚本详解 --------循环语句之for循环
【小程序】实现发动态功能
JVM内存和垃圾回收-08.方法区
redis
罗振宇折戟创业板/ B站回应HR称用户是Loser/ 腾讯罗技年内合推云游戏掌机...今日更多新鲜事在此...
Copycat CNN: Stealing Knowledge by Persuading Confession with Random Non-Labeled Data阅读心得
15 days to upgrade to fight monsters and become a virtual fashion creator
88.(cesium之家)cesium聚合图
开一个羽毛球馆大概需要多少钱?大约15万左右可以搞定!
随机推荐
码蹄集 - MT3029 - 新月轩就餐
WEB 渗透之越权
Mobile magic box CM201-1_CW_S905L2_MT7668_wire brush firmware package
华为云数据治理生产线DataArts,让“数据‘慧’说话”
西西成语接龙小助手
yarn详细入门教程
泰坦尼克号沉船数据之美——起于悲剧,止于浪漫
嵌入式系统驱动初级【6】——内核定时器
Compose 类型稳定性注解:@Stable & @Immutable
R语言使用yardstick包的gain_curve函数评估多分类(Multiclass)模型的性能、查看模型在多分类每个分类上的增益(gain)曲线(gain curve)
浙江数码代工M301H 免拆通刷_卡刷固件包(语音OK)
WPF 修改 ItemContainerStyle 鼠标移动到未选中项效果和选中项背景
如何提高员工积极性?
Minecraft HMCL 第三方启动器使用教程
WEB 渗透之SSTI 模板注入
为什么买域名必须实名认证?这样做什么原因?
Qt自动补全之QCompleter使用
response的contentType 几种类型
麒麟信安石勇博士荣获openEuler社区年度开源贡献之星
Mobile magic box CM211-1_YS foundry _S905L3B_RTL8822C_wire brush firmware package