Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

这道题给了我们一个数组,让我们求和为k的连续子数组的个数,博主最开始看到这道题想着肯定要建立累加和数组啊,然后遍历累加和数组的每个数字,首先看其是否为k,是的话结果 res 自增1,然后再加个往前的循环,这样可以快速求出所有的子数组之和,看是否为k,参见代码如下:

解法一:

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = , n = nums.size();
vector<int> sums = nums;
for (int i = ; i < n; ++i) {
sums[i] = sums[i - ] + nums[i];
}
for (int i = ; i < n; ++i) {
if (sums[i] == k) ++res;
for (int j = i - ; j >= ; --j) {
if (sums[i] - sums[j] == k) ++res;
}
}
return res;
}
};

上面的求累加和的方法其实并没有提高程序的执行效率,跟下面这种暴力搜索的解法并没有什么不同,博主很惊奇 OJ 居然这么大度,让这种解法也能通过,参见代码如下:

解法二:

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = , n = nums.size();
for (int i = ; i < n; ++i) {
int sum = nums[i];
if (sum == k) ++res;
for (int j = i + ; j < n; ++j) {
sum += nums[j];
if (sum == k) ++res;
}
}
return res;
}
};

论坛上大家比较推崇的其实是这种解法,用一个哈希表来建立连续子数组之和跟其出现次数之间的映射,初始化要加入 {0,1} 这对映射,这是为啥呢,因为我们的解题思路是遍历数组中的数字,用 sum 来记录到当前位置的累加和,我们建立哈希表的目的是为了让我们可以快速的查找 sum-k 是否存在,即是否有连续子数组的和为 sum-k,如果存在的话,那么和为k的子数组一定也存在,这样当 sum 刚好为k的时候,那么数组从起始到当前位置的这段子数组的和就是k,满足题意,如果哈希表中事先没有 m[0] 项的话,这个符合题意的结果就无法累加到结果 res 中,这就是初始化的用途。上面讲解的内容顺带着也把 for 循环中的内容解释了,这里就不多阐述了,有疑问的童鞋请在评论区留言哈,参见代码如下:

解法三:

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = , sum = , n = nums.size();
unordered_map<int, int> m{{, }};
for (int i = ; i < n; ++i) {
sum += nums[i];
res += m[sum - k];
++m[sum];
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/560

类似题目:

Two Sum

Continuous Subarray Sum

Subarray Product Less Than K

Find Pivot Index

参考资料:

https://leetcode.com/problems/subarray-sum-equals-k/

https://leetcode.com/problems/subarray-sum-equals-k/discuss/102153/Basic-Java-solution

https://leetcode.com/problems/subarray-sum-equals-k/discuss/134689/Three-Approaches-With-Explanation

https://leetcode.com/problems/subarray-sum-equals-k/discuss/102106/Java-Solution-PreSum-%2B-HashMap

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 560. Subarray Sum Equals K 子数组和为K的更多相关文章

  1. leetcode 560. Subarray Sum Equals K 、523. Continuous Subarray Sum、 325.Maximum Size Subarray Sum Equals k(lintcode 911)

    整体上3个题都是求subarray,都是同一个思想,通过累加,然后判断和目标k值之间的关系,然后查看之前子数组的累加和. map的存储:560题是存储的当前的累加和与个数 561题是存储的当前累加和的 ...

  2. LeetCode 560. Subarray Sum Equals K (子数组之和等于K)

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  3. [leetcode]560. Subarray Sum Equals K 和为K的子数组

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  4. [LeetCode] Continuous Subarray Sum 连续的子数组之和

    Given a list of non-negative numbers and a target integer k, write a function to check if the array ...

  5. [LeetCode] 560. Subarray Sum Equals K_Medium

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  6. [LeetCode] Subarray Product Less Than K 子数组乘积小于K

    Your are given an array of positive integers nums. Count and print the number of (contiguous) subarr ...

  7. [LeetCode] Subarray Sum Equals K 子数组和为K

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  8. 560. Subarray Sum Equals K 求和为k的子数组个数

    [抄题]: Given an array of integers and an integer k, you need to find the total number of continuous s ...

  9. 【LeetCode】560. Subarray Sum Equals K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

随机推荐

  1. 百度APP移动端网络深度优化实践分享(三):移动端弱网优化篇

    本文由百度技术团队“蔡锐”原创发表于“百度App技术”公众号,原题为<百度App网络深度优化系列<三>弱网优化>,感谢原作者的无私分享. 一.前言 网络优化解决的核心问题有三个 ...

  2. LeetCode 155:最小栈 Min Stack

    LeetCode 155:最小栈 Min Stack 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈. push(x) -- 将元素 x 推入栈中. pop() -- ...

  3. 洛谷 P2656 (缩点 + DAG图上DP)

    ### 洛谷 P2656 题目链接 ### 题目大意: 小胖和ZYR要去ESQMS森林采蘑菇. ESQMS森林间有N个小树丛,M条小径,每条小径都是单向的,连接两个小树丛,上面都有一定数量的蘑菇.小胖 ...

  4. PHP rand和mt_rand 区别

    mt_rand() 比rand() 快四倍使用方法 <?php//输出35echo(mt_rand(10,100));?>

  5. jquery实现移动端页面加载后,向上滚动指定距离无效引起的探索

    效果如下,页面加载完后向上滚动一段距离 最近一同事询问用jquery为何无法实现上面效果,查看代码后发现代码并没写错,   也正确引入了zepto.js,也不是版本问题(因为是移动端项目,出于性能和需 ...

  6. 图解Hyperf框架:Hyperf 的初始化

  7. linux部署java命令

    启动: #!/bin/bash source /etc/profile log() { echo `date +[%Y-%m-%d" "%H:%M:%S]` $1 } log &q ...

  8. WPF MVVM框架(5)

    前面几章节所讲到的内容, 基本上属于前端XAML的使用方法, 那么本章及后面的章节, 则会侧重于UI与业务分离如何分离 . UI与业务逻辑之间的互操作性,, 下面将介绍WPF中, 比较主流的MVVM框 ...

  9. 点击除指定区域外的空白处,隐藏div

    <script> $(document).click(function (e) { var $target = $(e.target); //点击.zanpl和.quanzipl以外的地方 ...

  10. NBIOT实现UDP协议的发送和接收(包含软件升级)

    源码下载: nbiot_module程序(java netbean) -> 提取码 UdpServer程序(C# vs2010) -> 提取码 QQ:505645074 前提条件:开NB卡 ...