Inscription
Poorly prefix hash,
up to sliding window
---鲁迅
Article Directory
Prefix hash
560. The sub-array whose sum is K (count the number of sub-arrays)
Because there is no constraint of positive integers, sliding windows cannot be used
Prefix and + hash table
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
mp=collections.defaultdict(int)
mp[0]=1
pre=0
count=0
for num in nums:
pre+=num
if pre-k in mp:
count+=mp[pre-k]
mp[pre]+=1
return count
325. The length of the longest sub-array whose sum is equal to k (the maximum length of the statistical sub-array)
325. The length of the longest subarray whose sum is equal to k
class Solution:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
n=len(nums)
# 上题存个数,这题存下标
pre_idx = defaultdict(int)
res=0
pre=0
# 忘了写这个
pre_idx[0] = -1
for i in range(n):
pre+=nums[i]
if pre not in pre_idx:
pre_idx[pre]=i
if pre-k in pre_idx:
res=max(res, i-pre_idx[pre-k])
return res
523. Contiguous sub-array sum
Free to watch
Sliding window
209. The smallest sub-array
There are positive integer constraints, using sliding window , O (n) O(n)O ( n )
But you can also use prefix and + dichotomy, O (n log n) O(n\log n)O ( nlogn)
class Solution {
public:
int minSubArrayLen(int target, vector<int> &nums) {
int sum = 0, l = 0, sz = nums.size() + 1;
for (int r = 0; r < nums.size(); ++r) {
sum += nums[r];
while (sum >= target) {
int cur_sz = r - l + 1;
if (cur_sz < sz) sz = cur_sz;
sum -= nums[l++];
}
}
return sz == nums.size() + 1 ? 0 : sz;
}
};