leetcode-560-Subarray-Sum-Equals-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:

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

分析


题目要求是从一个数组中,求连续子序列和为 k 的个数。数据量不是很大,可以用暴力枚举的方式,还有一种方式是使用哈希表辅助的方式,定义 sum[i] 为 0-i 的和,哈希表存的是 sum 以及和为 sum 的子序列的个数,只需要遍历一次序列,遍历的过程中求 sum,同时根据当前的 sum 求哈希表中 sum-k 对应的子序列的个数,将这些值加起来即可。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int subarraySum(int[] nums, int k) {
int sum = 0, result = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum-k)) {
result += map.get(sum-k);
}
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
return result;
}
}

相关问题


题目来源