# [LeetCode] 560. Subarray Sum Equals K 子数组和为K

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].

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = 0, n = nums.size();
vector<int> sums = nums;
for (int i = 1; i < n; ++i) {
sums[i] = sums[i - 1] + nums[i];
}
for (int i = 0; i < n; ++i) {
if (sums[i] == k) ++res;
for (int j = i - 1; j >= 0; --j) {
if (sums[i] - sums[j] == k) ++res;
}
}
return res;
}
};

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
int sum = nums[i];
if (sum == k) ++res;
for (int j = i + 1; j < n; ++j) {
sum += nums[j];
if (sum == k) ++res;
}
}
return res;
}
};

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = 0, sum = 0, n = nums.size();
unordered_map<int, int> m{{0, 1}};
for (int i = 0; i < n; ++i) {
sum += nums[i];
res += m[sum - k];
++m[sum];
}
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/560

Two Sum

Continuous Subarray Sum

Subarray Product Less Than K

Find Pivot Index

https://leetcode.com/problems/subarray-sum-equals-k/

https://leetcode.com/problems/subarray-sum-equals-k/discuss/102153/Basic-Java-solution

https://leetcode.com/problems/subarray-sum-equals-k/discuss/134689/Three-Approaches-With-Explanation

https://leetcode.com/problems/subarray-sum-equals-k/discuss/102106/Java-Solution-PreSum-%2B-HashMap

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2017-05-04 22:46  Grandyang  阅读(24384)  评论(9编辑  收藏  举报