主要是为了自己方便回忆思路。
思路:
滑动窗口 + 双指针 + 哈希表
用哈希表 key 对应水果 value 对应 出现次数
定义两个指针,l,r
r是循环内的指针,像探寻的小兵 (此处可以类比 长度最小的子数组,也是派一个搜寻,然后一个根据搜寻的结果进行移动
r 一直往前走,知道水果的种类超过了 2 也就是,map的大小超过了 2 就进入循环。
在循环中,不断删除水果篮里面的水果。注意:当水果篮的水果为 0 时,则删掉这个键值对,跳出循环。l 就往前走一步。
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = fruits.size();
unordered_map<int, int> cnt;
int l = 0,r = 0;
int ans = 0;
for(;r < n; r++)
{
// 碰到了新的水果
cnt[fruits[r]]++; //觉得这里有点像桶排序
while(cnt.size() > 2) //超过了两种水果
{
// 需要移动左边边界
// 找到左边的下标
auto it = cnt.find(fruits[l]);
//需要删除掉一个水果
it->second--;
// 如果出现次数为0,则删除该水果
if(it->second == 0)
cnt.erase(it);
l++;
}
ans = max(ans, r - l + 1);
}
return ans;
}
};