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
| class Solution { public int subarraysWithKDistinct(int[] nums, int k) { return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1); }
private int atMostKDistinct(int[] nums, int k) { int i = 0, j = 0; int[] count = new int[nums.length + 1]; int distinct = 0, res = 0;
while (j < nums.length) { if (count[nums[j]]++ == 0) { distinct++; }
while (distinct > k) { if (--count[nums[i++]] == 0) { distinct--; } }
res += j - i + 1; j++; }
return res; } }
|
References
992. Subarrays with K Different Integers