LeetCode Top 100 Liked Questions 560. Subarray Sum Equals K (Java版; 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 = 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].
classSolution{publicintsubarraySum(int[] nums,int k){//连续数组求和, 考虑前缀和
HashMap<Integer, Integer> map =newHashMap<>();
map.put(0,1);int sum =0;int res =0;for(int i=0; i<nums.length; i++){
sum += nums[i];int residual = sum - k;if(map.containsKey(residual)){
res += map.get(residual);}
map.put(sum, map.getOrDefault(sum,0)+1);}return res;}}