[Med] LeetCode 560. Subarray Sum Equals K
链接: https://leetcode.com/problems/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.
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
Example 1:
Input:nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
Note:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
Tag: Pre-Sum, HashMap
解题思路
这道题目是一个非常经典的pre-sum的做法。我们构建一个hashmap, 里面储存的是在遍历到i位之前的所有从0开始的subarray的和。比如说当i为3时,Map当中会储存[array[0]], [array[0]+array[1]], [array[0]+array[1]+array[2]]的三个subarray的和。我们在遍历数组的时候同时要累加当前遍历到的元素。total+=array[i]。然后此时我们只需要判断map当中是否出现过total-k就知道在这之前是否有subarray可以和当前total相减取得K这个值了。同时我们也可以知道在这之前有多少个subarray。
解法一:
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> presum = new HashMap<>();
//要添加0的原因是空的subarray总和就是0
presum.put(0, 1);
int total = 0, res = 0;
for(int num : nums){
total+=num;
if(presum.containsKey(total-k)){
res+=presum.get(total-k);
}
presum.put(total, presum.getOrDefault(total, 0)+1);
}
return res;
}
}