992. K 个不同整数的子数组(力扣)

题目:

给定一个正整数数组 A,如果 A 的某个子数组中不同整数的个数恰好为 K,则称 A 的这个连续、不一定独立的子数组为好子数组。
(例如,[1,2,3,1,2] 中有 3 个不同的整数:1,2,以及 3。)
返回 A 中好子数组的数目。

示例 1:

输入:A = [1,2,1,2,3], K = 2
输出:7
解释:恰好由 2 个不同整数组成的子数组:[1,2], [2,1],[1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

示例 2:

输入:A = [1,2,1,3,4], K = 3
输出:3
解释:恰好由 3 个不同整数组成的子数组:[1,2,1,3],[2,1,3], [1,3,4].

代码:

class Solution:
    def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
        return self.pro(A, K) - self.pro(A, K - 1)#从0到k的减去0到k-1的恰好是k个的
    def pro(self, A, K):
        l = len(A)
        left, right = 0, 0
        counter = collections.Counter()#储存每个数字的个数
        distinct = 0 #记录不同数字的个数
        res = 0
        while right < l:
            if counter[A[right]] == 0:
                distinct += 1
            counter[A[right]] += 1
            while distinct > K:#如果不同数字的个数不减到要求就一直移动左指针
                counter[A[left]] -= 1
                if counter[A[left]] == 0:#如果因为左指针的右移导致当前数字的个数为零了,那么distinct的个数也要减一
                    distinct -= 1
                left += 1
            res += right - left + 1
            right += 1
        return res

你可能感兴趣的:(力扣,leetcode,算法,指针)