> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/ladder_code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/ladder_code/facebook/subarray-sum-equals-k2sum-and-presum.md).

# Subarray Sum Equals K（2sum and presum）

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:**

1. The length of the array is in range \[1, 20,000].
2. The range of numbers in the array is \[-1000, 1000] and the range of the integer **k** is \[-1e7, 1e7].

分析：

本题只能two sum思想，不能用two pointers，因为可能有负数，所以当前的sum可能和前面好几个sum的diff == K. 用Map才能准确记录前面多少个subsum = cursum - K.(含有负数抵消的情况）

```
PrefixSum + Dictionary
> Time Complexity O(N)
> Space Complexity O(N)
```

这里没有presum数组，只有sum累积

这里map存个数 map\[sum]=count

对map和ret都是+=1不是=！！！！！

PYTHON MAP:MAP.GET(KEY,0)

```
 if we know SUM[0, i - 1] and SUM[0, j], then we can easily get SUM[i, j]. 因为不包含前数，所以Map[0]=1
```

```
import collections

class Solution:
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if not nums:
            return 0
        ret = 0
        n = len(nums)

        map = collections.defaultdict(int)
        map[0] = 1 #因为前面总是不包含，所以需要map[0]补足？
        sum=0
        for i in range(n):
            sum+=nums[i]
            if sum - k in map:
                ret += map[sum- k]#+= 不是 =
            map[sum] += 1 #+= 不是 =
        return ret
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nataliekung.gitbook.io/ladder_code/facebook/subarray-sum-equals-k2sum-and-presum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
