一道自认为很典型的滑动窗口问题,整理思路重新写一篇文章来当作笔记
思路
用两个列表进行记录,当前滑动窗口中一个元素出现了几次(注意,不管是a列表还是b列表的元素都不是唯一的,所以要采用这个方法来记录)如果大于等于匹配度k就将计数器加上1
from collections import deque
t = int(input())
for _ in range(t):
n, m, k = map(int, input().split())
a = [0]
b = [0]
a.extend(list(map(int, input().split())))
b.extend(list(map(int, input().split())))
rec = {}
mp = {}
q = deque()
for i in range(1, len(b)):
try:
rec[b[i]] += 1
except KeyError:
rec[b[i]] = 1
for key in a:
mp.update({key: 0})
try:
rec[key] += 0
except KeyError:
rec[key] = 0
match = cnt = 0
for i in range(1, m + 1):
q.append(a[i])
if mp[a[i]] < rec[a[i]]:
if rec[a[i]] != 0:
match += 1
mp[a[i]] += 1
if match >= k:
cnt += 1
for i in range(m + 1, n + 1):
if mp[q[0]] <= rec[q[0]]:
if rec[q[0]] != 0:
match -= 1
mp[q[0]] -= 1
q.popleft()
q.append(a[i])
if mp[a[i]] < rec[a[i]]:
if rec[a[i]] != 0:
match += 1
mp[a[i]] += 1
if match >= k:
cnt += 1
print(cnt)