难度困难174
给定一个正整数数组 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的子数组数量,因此通过滑动窗判断即可得出两种情况的子数组数量和,相减即为结果。
class Solution {
private:
int room[20001];
int subarrayswithmax(vector<int>& A, int K) {
memset(room, 0, sizeof(room));
int left = 0, right = 0;
int count = 0;
int res = 0;
while (right < A.size()) {
if (room[A[right]] == 0) {
count++;
}
room[A[right]]++;
right++;
while (count > K) {
room[A[left]]--;
if (room[A[left]] == 0) {
count--;
}
left++;
}
res += right - left;
}
return res;
}
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return subarrayswithmax(A,K) - subarrayswithmax(A, K - 1);
}
};