LC.P560[和为K的子数组] 方法一:前缀和12345678910111213class Solution { public int subarraySum(int[] nums, int k) { int n = nums.length, ans = 0; int[] sum = new int[n + 1]; for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + nums[i - 1]; for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { if (sum[j + 1] - sum[i] == k) ++ans; } } return ans; }} 时间复杂度:$O(n^2)$ 空间复杂度:$O(n)$ 方法二:前缀和+哈希表123456789101112131415class Solution { public int subarraySum(int[] nums, int k) { int pre = 0, ans = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for (int num : nums) { pre += num; if (map.containsKey(pre - k)) { ans += map.get(pre - k); } map.merge(pre, 1, Integer::sum); } return ans; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$