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:spa
Input:nums = [1,1,1], k = 2 Output: 2Note:code
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is >[-1e7, 1e7].
这道题开始并不容易想,由于不是典型的那种能够用DP解决的子数组类型的题。因为求的是子subarray和为K的总个数,只能想办法找出全部和为K的子数组,而后返回个数就能够。get
那么关键点就是怎么找出全部和为K的子数组,bruce force的方法显然不可行。突破点就是咱们能够把任意子数组的里面全部元素的和转化为两个子数组累计元素和之差,固然这个两个子数组指的是头元素是大数组第一个元素的连续子数组。这样一来,咱们用一个HashMap来记录每一个子数组元素和对应的次数就能够了。io
咱们从头开始读数组,记录下累计元素之和,把每次的和存在HashMap中,经过HashMap在每次读的过程当中咱们能够找出是否前面存在一个数组与当前数组之差等于K,这样咱们就能够找出因此子数组之和为K的状况。因为存在前面子数组和相同的状况,咱们用HashMap记录每一个和对应的次数就能够了。class
time: O(n), space: O(n)map
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); int sum = 0; int count = 0; for (int num : nums) { sum += num; if (map.containsKey(sum - k)) { count += map.get(sum - k); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return count; } }