-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
27 lines (24 loc) · 823 Bytes
/
Solution.java
File metadata and controls
27 lines (24 loc) · 823 Bytes
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
class Solution {
public int subarraysWithKDistinct(int[] nums, int k) {
int subMaxK = subarrayMostK(nums, k);
int reduceMaxK = subarrayMostK(nums, k - 1);
return subMaxK - reduceMaxK;
}
public int subarrayMostK ( int[] nums, int k){
int i = 0, j = 0, result = 0;
HashMap<Integer, Integer> map = new HashMap<>();
while (i < nums.length){
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
while (map.size() > k) {
map.put(nums[j], map.get(nums[j]) - 1);
if (map.get(nums[j]) == 0){
map.remove(nums[j]);
}
j++;
}
result += i - j + 1;
i++;
}
return result;
}
}