版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tc_To_Top/article/details/88958199
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:
- 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].
题目链接:https://leetcode.com/problems/subarray-sum-equals-k/
题目分析:前缀和,hashmap,没了
12ms,时间击败99.86%
class Solution {
public int subarraySum(int[] nums, int k) {
HashMap<Integer, Integer> mp = new HashMap<>();
int[] sum = new int[nums.length + 1];
for (int i = 1; i <= nums.length; i++) {
sum[i] = sum[i - 1] + nums[i - 1];
}
int ans = 0;
for (int i = 0; i < sum.length; i++) {
if (mp.containsKey(sum[i] - k)) {
ans += mp.get(sum[i] - k);
}
mp.put(sum[i], mp.getOrDefault(sum[i], 0) + 1);
}
return ans;
}
}