1class Solution {2public int subarraysWithKDistinct(int[] nums, int k) {3return count(nums, k) - count(nums, k - 1);4}56public int count(int[] nums, int k) {7HashMap<Integer, Integer> hm = new HashMap<>();89int left = 0, right = 0, ans = 0;1011while (right < nums.length) {12hm.put(nums[right], hm.getOrDefault(nums[right], 0) + 1);1314while (hm.size() == k + 1) {15hm.put(nums[left], hm.get(nums[left]) - 1);16if (hm.get(nums[left]) == 0) hm.remove(nums[left]);17left++;18}19ans += right - left + 1;20right++;21}22return ans;23}24}