Leetcode 992. K 个不同整数的子数组 题解

题目链接:https://leetcode-cn.com/problems/subarrays-with-k-different-integers/

在这里插入图片描述
在这里插入图片描述
滑动窗口,从左向右遍历
(1)读取一个元素,维护count数组记录出现的次数,如果是第一次出现,count++
(2)如果当前count > K,则左指针右移,直到 count = K
(3)在当前 count == K的前提下,用 t 存放左指针指向位置,继续右移,直到 count < K,否则 res++(记录满足条件的子数组个数)
(4)恢复左指针到 l ,将 l 到当前 t 中间的数组元素数据恢复
(5)重复(1)直到右指针达到数组末尾

代码如下:

class Solution {
public:
    int subarraysWithKDistinct(vector<int>& A, int K) {
        int len = A.size();
        int l = 0, r = 0;
        vector<int> cnt(len + 1, 0);
        int res = 0, count = 0;

        while(r < len) {
            if(!cnt[A[r]]) {
                count++;
            }
            cnt[A[r]]++;

            while(count > K) {
                cnt[A[l]]--;
                if(!cnt[A[l]]) {
                    count--;
                }
                l++;
            }

            int t = l;
            while(count == K) {
                res++;
                cnt[A[t]]--;
                if(!cnt[A[t]]) {
                    count--;
                }
                t++;
            }

            for(int i = l; i < t; i++) {
                if(!cnt[A[i]]) {
                    count++;
                }
                cnt[A[i]]++;
            }

            r++;
        }

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值