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].
Solution 1. Prefix Sum, O(N^2) runtime, O(N) space
1. compute a prefix sum of the input array;
2. for each subarray interval, check its sum equals to k, add 1 to the result counter if so. This step takes O(N^2) time.
class Solution { public int subarraySum(int[] nums, int k) { int n = nums.length; int[] prefixSum = new int[n + 1]; for(int i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + nums[i - 1]; } int count = 0; for(int i = 0; i < n; i++) { for(int j = i + 1; j <= n; j++) { if(prefixSum[j] - prefixSum[i] == k) count++; } } return count; } }
Solution 2. Prefix Sum with HashMap, O(N) runtime and space
1. Keep a running prefix sum and a hash map that stores the count of each different prefix sum value; Add (0, 1) to the hashmap, representing a sum of 0 for empty interval.
2. for a given prefix sum ps, check if there are prefix sums that equal to ps - k. Any such prefix sum of ps - k means there is an interval with sum k. For each such prefix sum, add 1 to the final counter.
3. add the current prefix sum to the hash map for later checks.
This solution can be easily modified to get all intervals that sum to k. Just augment the value in hashmap to have the current element index.
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); int prefixSum = 0, count = 0; map.put(0, 1); for(int i = 0; i < nums.length; i++) { prefixSum += nums[i]; count += map.getOrDefault(prefixSum - k, 0); map.put(prefixSum, map.getOrDefault(prefixSum, 0) + 1); } return count; } }
本文介绍了解决子数组求和等于特定值K的问题,提供了两种解决方案:一种使用前缀和方法的时间复杂度为O(N^2),另一种通过哈希映射优化至O(N)。这两种方法都能有效地找出数组中所有连续子数组,使得这些子数组的和等于给定的整数K。
2339

被折叠的 条评论
为什么被折叠?



