Poison

992. Subarrays with K Different Integers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public int subarraysWithKDistinct(int[] nums, int k) {
return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1);
}

private int atMostKDistinct(int[] nums, int k) {
int i = 0, j = 0; // [i, j]
int[] count = new int[nums.length + 1];
int distinct = 0, res = 0;

while (j < nums.length) {
if (count[nums[j]]++ == 0) {
// 当前字符是一个新的不重复字符
distinct++;
}

while (distinct > k) {
// 此时不重复字符数已经大于 k, 缩小窗口
if (--count[nums[i++]] == 0) {
distinct--;
}
}

res += j - i + 1;
j++;
}

return res;
}
}
Reference

992. Subarrays with K Different Integers