public class Solution {
public int SubarraySum(int[] nums, int k) {
int sum = , result = ;
Dictionary<int, int> preSum = new Dictionary<int, int>();
preSum.Add(, ); for (int i = ; i < nums.Length; i++)
{
sum += nums[i];
if (preSum.ContainsKey(sum - k))
{
result += preSum[sum - k];
}
if (preSum.ContainsKey(sum))
{
preSum[sum]++;
}
else
{
preSum.Add(sum, );
}
} return result;
}
}

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

补充一个python的实现,和上面的思路一样:

 class Solution:
def subarraySum(self, nums: 'List[int]', k: int) -> int:
sums = 0
count = 0
dic = dict()
for n in nums:
if sums in dic.keys():
dic[sums] += 1
else:
dic[sums] = 1
sums += n
dif = sums - k
if dif in dic.keys():
count += dic[dif]
return count

下面进行解释,字典dic中存储的是某一个连续和的出现频率。例如nums=[1,1,1],k=2。

第一次循环时,sums等于第零项的值0,则有{0:1},表示连续和为0的情况出现了1次。

第二次循环时,sums等于第一项的值1,则有{0:1,1:1},表示连续和为1出现了1次。

第三次循环时,sums等于前两项的值2,则有{0:1,1:1,2:1},表示连续和为2出现了1次。

第四次循环时,sums等于前三项的值3,则有{0:1,1:1,2:1,3:1},表示连续和为3出现了1次。

每一次循环的过程中都判断sums-k是否在字典dic中出现过,

如果出现过,则表示到当前位置的前x项中,包含有连续和为k的子集。

这一点是数学的技巧,也是提高效率的关键。

leetcode560的更多相关文章

  1. leetcode560题解【前缀和+哈希】

    leetcode560.和为K的子数组 题目链接 算法 前缀和+哈希 时间复杂度O(n). 在解决这道题前需要先清楚,一个和为k的子数组即为一对前缀和的差值. 1.我们假设有这么一个子数组[i,j]满 ...

  2. [Swift]LeetCode560. 和为K的子数组 | Subarray Sum Equals K

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

  3. LeetCode560. Subarray Sum Equals K

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

随机推荐

  1. postman操作练习用例

    1.注册用户:http://api.nnzhp.cn/api/user/user_reg 2.登录用户:http://api.nnzhp.cn/api/user/login 3.添加学生:http:/ ...

  2. JavaScript之作用域

    1. 作用域 变量能够起作用的范围,作用域分为全局作用域和局部作用域 全局作用域: 1. 最外层函数或者在最外层函数外通过var定义的变量: 2. window对象的属性和方法具有全局作用域: 3. ...

  3. TestLink测试管理工具的使用举例—第一篇

    本博客用来详细说明TestLink测试管理工具的使用方法,前两篇博客已经详细说明了TestLink工具的下载,安装及基本登录功能,本篇开始说明其工具的具体使用! 下载安装TestLink工具之后,我们 ...

  4. DAY 04运算符与流程控制

    输入输出补充: python2与python3的输入输出不同 python2中有两种用户 输入方式,一种是raw_input,和input raw_input与python3的input是相同的 而p ...

  5. Windows10 VS2017 C++信号处理

    #include "pch.h" #include <iostream> #include <csignal> #include <windows.h ...

  6. Linux 驱动——Led驱动1

    led_drv.c驱动文件: #include <linux/module.h>#include <linux/kernel.h>#include <linux/init ...

  7. vue 安卓5.1 ios9 兼容性 白屏问题

    // 针对安卓4.4/ios的兼容 import 'babel-polyfill' import Es6Promise from 'es6-promise' require('es6-promise' ...

  8. 多线程callable使用方法

    Runnable是执行工作的独立任务,但是它不返回任何值.在JavaSE5中引入的Callable是一种具有类型参数的泛型,它的类型参数表的是从方法call()中返回的值,并且必须使用Executor ...

  9. Linux安装软件出现 “Unable to locate package xxx”错误

    使用新购入的阿里云服务器ECS,预装的Ubuntu,然后想要利用 xrdp 进行远程登陆,但是在输入命令: apt-get install xrdp 出现了 E;Unable to locate pa ...

  10. ipv4-only网络环境下访问ipv6站点

    使用6plat.org+openVPN(无需资金投入)进入ipv6网络 这里我们主要使用的是6plat.org提供的“46模块——IPv4到IPv6”功能,需要配合openVPN这个软件,支持wind ...