1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int subarraysWithKDistinct(vector<int>& nums, int k) { int n = nums.size(); function<int(int)> atMostDistinct = [&](int k) { int res = 0; vector<int> freq(n + 1); for (int left = 0, right = 0, cnt = 0; right < n; ++right) { if (++freq[nums[right]] == 1) ++cnt; while (cnt > k) if (--freq[nums[left++]] == 0) --cnt; res += right - left + 1; } return res; }; return atMostDistinct(k) - atMostDistinct(k - 1); } };
|