560. 和为 K 的子数组
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e2e7f012607a93d089fdf5aaf7d2efbc.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c320a967db98e40cc05df9c14cc0d6cb.png)
解法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/94941d90ea0d68429f0bedad16106bc4.png)
python
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
res=0
for i in range(len(nums)+1):
j=i-1
b=0
while j>-1 :
print(j,i)
b=b+nums[j]
if b ==k:
res+=1
j=j-1
return res
c++
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int> hash;
int sum=0;
int res=0;
hash[0]=1;
for(int i =0;i< nums.size();++i){
sum+=nums[i];
if (hash.count(sum-k)){
cout<<sum;
cout<<k;
res+=hash[sum-k];}
hash[sum]++;
}
return res;
}
};
523. 连续的子数组和
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4b04df74f406e9e56511b7ae25ee0d18.png)
解法
python
class Solution:
def checkSubarraySum(self, nums: List[int], k: int) -> bool:
res=0
for i in range(len(nums)+1):
j=i-1
sum1=0
while j>-1:
sum1+=nums[j]
if sum1%k==0 and (i-j)>1:
return True
j=j-1
return False
c++
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
int m = nums.size();
if (m < 2) {
return false;
}
unordered_map<int, int> mp;
mp[0] = -1;
int remainder = 0;
for (int i = 0; i < m; i++) {
remainder = (remainder + nums[i]) % k;
if (mp.count(remainder)) {
int prevIndex = mp[remainder];
if (i - prevIndex >= 2) {
return true;
}
} else {
mp[remainder] = i;
}
}
return false;
}
};
525. 连续数组
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/46dbea3bfd206c8dff273791a82d667a.png)
解法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/93e9d95aea30f2eec30b85729289dc01.png)
python
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
for i in range(len(nums)):
if nums[i] ==0:
nums[i]=-1
a=dict()
sum1=0
lenth=0
a[0]=-1
for i in range(len(nums)):
sum1=sum1+nums[i]
if sum1 in a:
if i-a[sum1]>lenth :
lenth=i-a[sum1]
else:
a[sum1]=i
return lenth
c++
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int,int> hash;
int sum=0;
int maxlen=0;
hash[0]=-1;
for (int i =0;i<nums.size();++i){
if (nums[i]==0){
nums[i]=-1;}
}
for(int i =0;i<nums.size();++i){
sum+=nums[i];
if (hash.count(sum)){
if ( i-hash[sum]>maxlen ){
maxlen=i-hash[sum];
cout <<i;
cout<<maxlen;
}
}
else{
hash[sum]=i;
}
}
return maxlen;
}
};