---
# System prepended metadata

title: 0560. Subarray Sum Equals K
tags: [Leetcode, FaceBook, Prefix Sum, Medium]

---

# 0560. Subarray Sum Equals K
###### tags: `Leetcode` `Medium` `Prefix Sum` `FaceBook`
Link: https://leetcode.com/problems/subarray-sum-equals-k/
## 思路
PrefixSum + HashMap(Two Sum)
## Code
```java=
class Solution {
    public int subarraySum(int[] nums, int k) {
        int[] prefixSum = new int[nums.length+1];
        prefixSum[0] = 0;
        for(int i = 1;i < nums.length+1;i++){
            prefixSum[i]+=prefixSum[i-1]+nums[i-1];
        }
        HashMap<Integer,Integer> hashMap = new HashMap();
        int count = 0;
        for(int sum:prefixSum){

//            System.out.println(sum+" "+hashMap.get(sum));
            if(hashMap.containsKey(sum-k)){
                count += hashMap.get(sum-k);
            }
            hashMap.put(sum, hashMap.getOrDefault(sum,0)+1);
        }
        return count;
    }
}
```