本文主要是介绍【重点】【前缀和】560. 和为 K 的子数组,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
解法1:哈希表
class Solution {public int subarraySum(int[] nums, int k) {int[] sumArray = new int[nums.length];Map<Integer, Integer> sumToCountMap = new HashMap<>();for (int i = 0; i < nums.length; ++i) {if (i == 0) {sumArray[i] = nums[i];} else {sumArray[i] = nums[i] + sumArray[i - 1];}int origin = sumToCountMap.getOrDefault(sumArray[i], 0);sumToCountMap.put(sumArray[i], origin + 1);}int res = sumToCountMap.getOrDefault(k, 0);for (int i = 0; i < sumArray.length; ++i) {int origin = sumToCountMap.get(sumArray[i]);if (origin > 1) {sumToCountMap.put(sumArray[i], origin - 1);} else {sumToCountMap.remove(sumArray[i]);}res += sumToCountMap.getOrDefault(sumArray[i] + k, 0);}return res;}
}
解法2:前缀和+哈希表
具体参见《算法小抄》。
class Solution {public int subarraySum(int[] nums, int k) {int res = 0, preSum = 0;Map<Integer, Integer> map = new HashMap<>();map.put(0, 1);for (int i = 0; i < nums.length; ++i) {preSum += nums[i];if (map.containsKey(preSum - k)) { // 注意:这里只能是'-'res += map.get(preSum - k);}map.put(preSum, map.getOrDefault(preSum, 0) + 1);}return res;}
}
这篇关于【重点】【前缀和】560. 和为 K 的子数组的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!