【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

思路:
恰好K个不同数字种类的子数组个数 = 最多K个不同数字种类子数组的个数 - 最多K - 1个不同数字种类子数组的个数
问题转化成:求由最多 K 个不同整数组成的子数组的个数

class Solution {
     
public:
    int getAtMoskK(vector<int>& A, int K) {
     
        int n = A.size();
        int left = 0, right = 0, ret = 0;
        unordered_map<int, int> mp; //记录每个数字出现的次数
        int c = 0; //不同数字的种类
        while (right < n) {
     
            if (mp[A[right]] == 0) //mp[A[right]]=0,说明right这个位置是新的数字,种类+1
                c++;
            mp[A[right]]++; //右指针指向的数字个数+1
            
            //如果当前不同数字的种类大于K,移动左指针
            while (c > K) {
     
                mp[A[left]]--;
                if (mp[A[left]] == 0)
                    c--;
                left++;
            }
            ret += right - left + 1;
            right++;
        }

        return ret;
    }

    int subarraysWithKDistinct(vector<int>& A, int K) {
     
        return getAtMoskK(A, K) - getAtMoskK(A, K - 1);
    }
};

再次附上很赞的大佬题解 https://leetcode-cn.com/problems/subarrays-with-k-different-integers/solution/cong-zui-jian-dan-de-wen-ti-yi-bu-bu-tuo-7f4v/

你可能感兴趣的:(刷题,leetcode)