标签:number nal who numbers get The run ota HERE
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:
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; } }
[LeetCode 560] Subarray Sum Equals K
标签:number nal who numbers get The run ota HERE
原文地址:https://www.cnblogs.com/lz87/p/11601300.html