public class Solution {
public int subarraysWithKDistinct(int[] A, int K) {
return atMostK(A, K) - atMostK(A, K - 1);
}
private int atMostK(int[] A, int K)
{
int n = A.length;
if (n == 0 || K == 0) {
return 0;
}
int res = 0;
int l = 0, r = 0;
Map<Integer, Integer> map = new HashMap<>();
for (; r < n; r++) {
int ri = A[r];
map.put(ri, map.getOrDefault(ri, 0) + 1);
while (map.size() > K) {
int li = A[l];
if (map.get(li) == 1) {
map.remove(li);
}
else {
map.put(li, map.get(li) - 1);
}
l++;
}
res += r - l + 1;
}
return res;
}
}
利用双指针滑动窗口解决
k个不同整数的子数组
最新推荐文章于 2022-05-05 19:42:38 发布