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].

提示:

1 <= A.length <= 20000
1 <= A[i] <= A.length
1 <= K <= A.length

思路

双指针(滑动窗口)
本质上是在枚举符合条件的右端点

class Solution:
    def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
        n = len(A)
        counter = collections.defaultdict(lambda: 0)
        ans = 0
        left, right = 0, 0
        while right < n:
            counter[A[right]] += 1
            right += 1
            while len(counter.keys()) > K:
                counter[A[left]] -= 1
                if counter[A[left]] == 0:
                    counter.pop(A[left])
                left += 1
            if len(counter.keys()) == K:
                l = left
                tmp_cnt = counter.copy()
                while len(tmp_cnt.keys()) == K:
                    # print(A[l:right])
                    tmp_cnt[A[l]] -= 1
                    if tmp_cnt[A[l]] == 0:
                        tmp_cnt.pop(A[l])
                    l += 1
                    ans += 1
        return ans

992. K 个不同整数的子数组_第1张图片

你可能感兴趣的:(Python)