classSolution:defcountSubarrays(self, nums: List[int], k:int)->int:
n =len(nums)
k_idx =0
p =[0]*(n +1)for i, v inenumerate(nums):
p[v]= i
while nums[k_idx]!= k:
k_idx +=1# s个比k小,s个比k大# s个比k小,s + 1个比k大
left, right = k -1, n - k
lefts, rights =[],[]# 左边的情况
small, big =0,0for i inrange(k_idx -1,-1,-1):if nums[i]< k:
small +=1else:
big +=1
lefts.append([small, big])# 右边的情况
small, big =0,0for i inrange(k_idx +1, n):if nums[i]< k:
small +=1else:
big +=1
rights.append([small, big])
ans =1# 自己# small - big#print(lefts)#print(rights)
lefts_diff =[]for small, big in lefts:
lefts_diff.append(big - small)
rights_diff =[]for small, big in rights:
rights_diff.append(big - small)# print(lefts_diff)# print(rights_diff)# 两个和要等于0或者1
ans =1# 自己for diff in lefts_diff:if diff ==0or diff ==1:
ans +=1for diff in rights_diff:if diff ==0or diff ==1:
ans +=1
rights_diff.sort()for num in lefts_diff:
need1 =-num
need2 =1- num
i = bisect_left(rights_diff, need1)
j = bisect_right(rights_diff, need2)
ans += j - i
return ans