Level:
Medium
Subject description:
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:
- 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].
Analysis of ideas:
Given an array of integers and a number k, which need to find the sum of the number k of successive subarray solved sum [i, j] = the number of target, obtained sum [0, i] and the sum [0, j] can know the sum [i, j]. Because we require all sum (0, i) = sum (0, j) - k of the sum (0, i), then if sum (0, i1) = sum (0, i2), you can directly save a value sum (0, i) is equal to the number of sub-array count value, and then use a HashMap saved.
Code:
public class Solution{
public int subarraySum(int []nums,int k){
if(nums==null||nums.length==0)
return 0;
int res=0;
HashMap<Integer,Integer>map=new HashMap<>();//键保存sum(0,i),值表示其相同值出现的次数
map.put(0,1);
int sum=0;
for(int i=0;i<nums.length;i++){
sum=sum+nums[i]; //表示sum(0,j)
if(map.containsKey(sum-k)){
res=res+map.get(sum-k);
}
map.put(sum,map.getOrDefault(sum,0)+1);
}
return res;
}
}