<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>

<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>
	<li><code>-10<sup>7</sup> &lt;= k &lt;= 10<sup>7</sup></code></li>
</ul>

#include <unordered_map>

struct Solution {

	int subarraySum(std::vector<int> const& nums, int k) {
		std::unordered_map<int, int> sum2Count;
		sum2Count.reserve(1000);
		int sum = 0;
		int count = 0;

		sum2Count.emplace(0, 1);

		for (int i = 0; i < nums.size(); ++i) {
			sum += nums[i];

			auto it = sum2Count.find(sum - k);

			// Если не нашли, то продолжим
			if (it != sum2Count.end()) {
				count += it->second;
			}

			// increase sums count
			{
				auto it = sum2Count.find(sum);

				// Если не нашли, то вставляем первую сумму в единственном экземпляре
				if (it == sum2Count.end()) {
					sum2Count.emplace(sum, 1);
				}
				else
					++it->second;
			}
		}

		return count;
	}
};
43383