class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = fruits.size();
unordered_map<int,int> hash;
int i = 0,res = 0;
for(int j = 0;j < n;j ++)
{
hash[fruits[j]] ++;
while(hash.size() > 2) //滑动窗口的while部分就是在缩小窗口
{ //while中的条件就是在何时应该缩小窗口
auto k = hash.find(fruits[i]);//while下执行的就是缩小窗口应该做什么
k->second --;
if(k->second == 0) hash.erase(k);
i ++;
}
res = max(res,j - i + 1);
}
return res;
}
};
lc904.水果成篮(滑动窗口)
最新推荐文章于 2024-07-24 22:13:06 发布