
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
Constraints:
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].
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/subarray-sum-equals-k 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
用map进行存储,map.containsKey 判断是否存在 适合的值,mp.get 获取适合的数量
数量和即为所求。
public class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0, pre = 0;
HashMap < Integer, Integer > mp = new HashMap < > ();
mp.put(0, 1);
for (int i = 0; i < nums.length; i++) {
pre += nums[i];
if (mp.containsKey(pre - k))
count += mp.get(pre - k);
mp.put(pre, mp.getOrDefault(pre, 0) + 1);
}
return count;
}
}检出map集合中有没有包含Key为key的元素,如果有则返回true,否则返回false。
根据map集合中元素的Key来获取相应元素的Value
向map集合中添加Key为key,Value为value的元素,当添加成功时返回null,否则返回value。
就是说Map集合中的Key是不能重复的,这就类似于Set集合中元素不能重复,但是Map集合中的Value是可以重复。