problem:2958. 最多 K 个重复元素的最长子数组
思路:维护滑动窗口的窗口内各个元素至多出现k次即可。nums[i]<=$10^9$,要离散化一下。
Accode:
class Solution {
public:
int maxSubarrayLength(vector<int>& nums, int k) {
unordered_map<int,int> dict;
int len = nums.size();
int sum = 0, ans = 0;
int left = 0;
for (int i = 0; i < len; i++) {
dict[nums[i]]++;
sum += 1;
if (dict[nums[i]] > k) {
for (int j = left; j < i; j++) {
dict[nums[j]]--;
sum -= 1;
if (dict[nums[i]] <= k) {
left = j + 1;
break;
}
}
}
ans = max(ans, sum);
}
return ans;
}
}
;
时间复杂度:$o(n)$