classIWindow {
public:virtualvoid add(int& num) =0;
virtualvoiderase(int& num) =0;
virtualboolcheck(int& num) =0;
virtual~IWindow() {}
};
classWindow:public IWindow {
private:int _t;
unordered_map<int,int> _map;
public: Window(int threshold): _t(threshold) {}
voidadd(int& num) override {
_map[num]++;
}
voiderase(int& num) override {
_map[num]--;
}
boolcheck(int& num) override {
return _map[num] == _t;
}
};
classSolution {
private: unique_ptr<IWindow> _w;
public:int maxSubarrayLength(vector<int>& nums, int k) {
_w = make_unique<Window>(k);
int n = nums.size();
int left =0, right =0, res =0;
while (right < n) {
int num = nums[right++];
while (_w->check(num)) _w->erase(nums[left++]);
_w->add(num);
res = max(res, right-left);
}
return res;
}
};
不囉嗦版
classSolution {
private: unordered_map<int,int> cnt;
public:int maxSubarrayLength(vector<int>& nums, int k) {
int n = nums.size(), left =0, right =0, res =0;
while (right < n) {
int num = nums[right++];
while (cnt[num] == k) {
cnt[nums[left++]]--;
}
cnt[num]++;
res = max(res, right - left);
}
return res;
}
};