计算和的值次数
# 建立哈希表
hashmap = defaultdict(int,{0:1})
#一次遍历做法,遍建立前缀和变边变更哈希表
for x in nums:
total += x
r = total
l = r - total
ans += hashmap[l]
hashmap[r]+= 1
return ans
和为奇数的和的次数
# 初始化
odd = 0
even = 1
for x in nums :
total += x
ans += odd if total % 2 ==0 else even
if total % 2 ==0:
even +=1
else :
odd +=1
return ans
统计0和1具有相同数量的的子数组个数(525.连续数组)
#建立哈希表
hashmap = defaultdict(int,{0,-1})
# 统计前缀和维护0和1的差值
cnt = ans = 0
for i , x in emumerate(num):
if x:
cnt += 1
else:
cnt -= 1
if cnt in hashmap :
ans = max(ans,i - hashmap[cnt])
else:
hashmap[cnt]=i
return ans