文章目录
- 题目
- 代码(9.27 首刷看解析)
题目
Leetcode 992. K 个不同整数的子数组
代码(9.27 首刷看解析)
滑动窗口,恰好转换为:最多K个不同的数 - 最多K-1个不同的数
class Solution {
public:int subarraysWithKDistinct(vector<int>& nums, int k) {return help(nums, k) - help(nums, k-1);}int help(vector<int>& nums, int k) {int n = nums.size();vector<int> window(n+1);int l = 0, r = 0;int res = 0;int cur = 0;while(r < n) {int num = nums[r++];if(!window[num])cur++;window[num]++;while(cur > k) {int num2 = nums[l++];window[num2]--;if(!window[num2])cur--;}res += r-l;}return res;}
};
还可以看一下这个类似的题:1248. 统计「优美子数组」