1
class Solution {
2
public int subarraysWithKDistinct(int[] nums, int k) {
3
return count(nums, k) - count(nums, k - 1);
4
}
5

6
public int count(int[] nums, int k) {
7
HashMap<Integer, Integer> hm = new HashMap<>();
8

9
int left = 0, right = 0, ans = 0;
10

11
while (right < nums.length) {
12
hm.put(nums[right], hm.getOrDefault(nums[right], 0) + 1);
13

14
while (hm.size() == k + 1) {
15
hm.put(nums[left], hm.get(nums[left]) - 1);
16
if (hm.get(nums[left]) == 0) hm.remove(nums[left]);
17
left++;
18
}
19
ans += right - left + 1;
20
right++;
21
}
22
return ans;
23
}
24
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0