给定一个正整数数组 A,如果 A 的某个子数组中不同整数的个数恰好为 K,则称 A 的这个连续、不一定不同的子数组为好子数组。
(例如,[1,2,3,1,2] 中有 3 个不同的整数:1,2,以及 3。)
返回 A 中好子数组的数目。
解法:用最多为k的数量减去最多为k-1的数量即为恰好为k的数量。
class Solution:
def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
length = len(A)
def GetNumAtMostK(k):
left, right = 0, 0
ans = 0
counter = {}
distant = 0
while right < length:
i = A[right]
if counter.get(i, 0) == 0:
distant += 1
counter[i] = counter.get(i, 0) + 1
while distant > k:
counter[A[left]] -= 1
if counter[A[left]] == 0:
distant -= 1
left += 1
right += 1
ans += right - left + 1
return ans
return GetNumAtMostK(K) - GetNumAtMostK(K - 1)