Leetcode 560[medium]. Subarray Sum Equals K

来源:互联网 发布:python selenium实战 编辑:程序博客网 时间:2024/05/16 06:26

难度:medium

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 = 2Output: 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]
思路:给定一个list,找到其中所有和等于K的连续subarray。返回subarray的总数。
          用一个哈希表来建立连续子数组之和跟其出现次数之间的映射。
          初始化要加入{0,1}这对映射,是因为我们的解题思路是遍历数组中的数字,用sum来记录到当前位置的累加和,我们建立哈希表的目的是为了可以快速的查找sum-k是否存在,即是否有连续子数组的和为sum-k,如果存在的话,那么和为k的子数组一定也存在,这样当sum刚好为k的时候,那么数组从起始到当前位置的这段子数组的和就是k,满足题意,如果哈希表中实现没有m[0]项的话,这个符合题意的结果就无法累加到结果res中。
         count.get()函数用于运算中出现的数值相同的sum。



原创粉丝点击