-
Notifications
You must be signed in to change notification settings - Fork 14
/
Solution992.java
40 lines (32 loc) · 1.08 KB
/
Solution992.java
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
31
32
33
34
35
36
37
38
39
40
package leetcode.slidingwindow;
import java.util.HashMap;
public class Solution992 {
public static void main(String[] args) {
// 2
System.out.println(new Solution992().subarraysWithKDistinct(new int[]{1, 2}, 1));
}
public int subarraysWithKDistinct(int[] nums, int k) {
return doSubarraysWithKDistinct(nums, k) - doSubarraysWithKDistinct(nums, k - 1);
}
private int doSubarraysWithKDistinct(int[] nums, int k) {
int res = 0;
HashMap<Integer, Integer> numCount = new HashMap<>();
int left = 0, right = 0;
while (right < nums.length) {
numCount.put(nums[right], numCount.getOrDefault(nums[right], 0) + 1);
if (numCount.get(nums[right]) == 1) {
k--;
}
while (k < 0) {
Integer count = numCount.get(nums[left]);
if (count == 1) {
k++;
}
numCount.put(nums[left++], --count);
}
res += right - left + 1;
right++;
}
return res;
}
}