LeetCode:992. K 个不同整数的子数组————困难

题目
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

解题思路

  • 双指针。
  • 通过读题,我们可以转换一下思路,题目中要求写出A中好子数组的个数。
  • 我们可以用至少 K -1个不同整数的子数组个数 - 至少 K个不同整数的子数组个数就是答案。

Code

class Solution:
    def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
        def func(A,K):
            n = len(A)
            i = 0
            res = 0 
            # 窗口内需要维护的变量
            diff_nums = 0
            counter = collections.defaultdict(int)  #统计数组中各数字出现的个数
            for j in range(n):
                # 扩大窗口
                counter[A[j]] += 1
                if counter[A[j]] == 1:
                    diff_nums += 1

                # 如果找到以i开头满足条件的子数组了,就更新答案并缩小窗口
                while diff_nums > K:
                    res += n-j
                    counter[A[i]] -= 1
                    if counter[A[i]] == 0:
                        diff_nums -= 1
                    i += 1
            return res
        return func(A,K-1) - func(A,K)


运行结果
LeetCode:992. K 个不同整数的子数组————困难_第1张图片

你可能感兴趣的:(Leetcode算法刷题,指针,leetcode,算法,python)