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] Subarray Sum Equals K 子数组和为K的更多相关文章

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

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

  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] Continuous Subarray Sum 连续的子数组之和

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

  4. LeetCode - Subarray sum equals k

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

  5. LeetCode 209. Minimum Size Subarray Sum (最短子数组之和)

    Given an array of n positive integers and a positive integer s, find the minimal length of a contigu ...

  6. [LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组

    Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...

  7. [leetcode]523. Continuous Subarray Sum连续子数组和(为K的倍数)

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

  8. 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题是存储的当前累加和的 ...

  9. LeetCode 560. 和为K的子数组(Subarray Sum Equals K)

    题目描述 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数. 示例 1 : 输入:nums = [1,1,1], k = 2 输出: 2 , [1,1] 与 [1,1] ...

随机推荐

  1. ES6 中 Promise 详解

    Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果.从语法上说,Promise 是一个对象,从它可以获取异步操作的消息.Promise 提供统一的 API ...

  2. Tomcat优化内存以及连接数

    公司的一个服务器使用Tomcat6默认配置,在后台一阵全点击服务器就报废了,查了一下就要是PERMSIZE默认值过小造成(16-64) TOMCAT_HOME/bin/catalina.sh 添加一行 ...

  3. Beta第七天

    听说

  4. java-JProfiler(一)-安装以及简介

    一.下载 下载http://www.ej-technologies.com/download/jprofiler/files 目前网上有9.2版本的使用方式,10.暂时还无法完美使用 可以下载zip包 ...

  5. Beta敏捷冲刺每日报告——Day5

    1.情况简述 Beta阶段Scrum Meeting 敏捷开发起止时间 2017.11.6 00:00 -- 2017.11.7 00:00 讨论时间地点 2017.11.6 早9:30,电话会议会议 ...

  6. Beta版本敏捷冲刺每日报告——Day3

    1.情况简述 Beta阶段第三次Scrum Meeting 敏捷开发起止时间 2017.11.4 08:00 -- 2017.11.4 22:00 讨论时间地点 2017.11.4晚9:00,软工所实 ...

  7. 详谈C++虚函数表那回事(一般继承关系)

    沿途总是会出现关于C++虚函数表的问题,今天做一总结: 1.什么是虚函数表: 虚函数(Virtual Function)是通过一张虚函数表(Virtual Table)来实现的.简称为V-Table. ...

  8. Flask 学习 十五 性能

    记录影响性能的数据库查询 app/main/views.py from flask_sqlalchemy import get_debug_queries @main.after_app_reques ...

  9. js 点击 返回顶部 动画

    附上效果图 触发前 触发后 HTML代码: CSS代码 JS代码 由于复制文本太丑了 所以直接放的图片  但是我在评论区把js代码又复制了一边 以便你们使用

  10. emqtt 试用(七)追踪

    追踪 EMQ 消息服务器支持追踪来自某个客户端(Client)的全部报文,或者发布到某个主题(Topic)的全部消息. 追踪客户端(Client): ./bin/emqttd_ctl trace cl ...