# 992. Subarrays with K Different Integers

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A  good  if the number of different integers in that subarray is exactly K.

(For example, [1,2,3,1,2] has 3 different integers: 12, and 3.)

Return the number of good subarrays of A.

Example 1:

Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:

Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Note:

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

class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return helper(A, K) - helper(A, K - 1);
}
int helper(vector<int>& A, int K) {
int n = A.size(), res = 0, left = 0;
unordered_map<int, int> numCnt;
for (int i = 0; i < n; ++i) {
if (numCnt[A[i]] == 0) --K;
++numCnt[A[i]];
while (K < 0) {
if (--numCnt[A[left]] == 0) ++K;
++left;
}
res += i - left + 1;
}
return res;
}
};

class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return helper(A, K) - helper(A, K - 1);
}
int helper(vector<int>& A, int K) {
int n = A.size(), res = 0, left = 0;
unordered_map<int, int> numCnt;
for (int i = 0; i < n; ++i) {
++numCnt[A[i]];
while (numCnt.size() > K) {
if (--numCnt[A[left]] == 0) numCnt.erase(A[left]);
++left;
}
res += i - left + 1;
}
return res;
}
};

class Solution {
public:
int subarraysWithKDistinct(vector<int>& A, int K) {
return helper(A, K) - helper(A, K - 1);
}
int helper(vector<int>& A, int K) {
int n = A.size(), res = 0, left = 0;
unordered_map<int, int> num2idx;
for (int i = 0; i < n; ++i) {
num2idx[A[i]] = i;
while (num2idx.size() > K) {
if (num2idx[A[left]] == left) num2idx.erase(A[left]);
++left;
}
res += i - left + 1;
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/992

Number of Substrings Containing All Three Characters

Count Number of Nice Subarrays

Replace the Substring for Balanced String

Max Consecutive Ones III

Binary Subarrays With Sum

Shortest Subarray with Sum at Least K

Minimum Size Subarray Sum

Longest Substring with At Most Two Distinct Characters

Longest Substring with At Least K Repeating Characters

Longest Substring with At Most K Distinct Characters

https://leetcode.com/problems/subarrays-with-k-different-integers/

https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/523136/JavaC%2B%2BPython-Sliding-Window

https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/235235/C%2B%2BJava-with-picture-prefixed-sliding-window

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation