说白了就是:找最多包含两种元素的最长子串,返回其长度
值得注意的是,当窗口内有三种种类时,左窗口边界是要向右移动到窗口内只剩两种种类,而不是什么先进先出!比如 [1,0,1,4,1,4,1,2,3]
法一:unordered_map
class Solution { public: int totalFruit(vector<int>& fruits) { int size = fruits.size(),resLenth = 0,left = 0,right; unordered_map<int,int> numAdded; for(right = 0;right < size;++right){ if(numAdded.size() == 2 && numAdded.find(fruits[right]) == numAdded.end()){ resLenth = max(resLenth,right - left); while(1){ --numAdded[fruits[left]]; if(numAdded[fruits[left]] == 0){ numAdded.erase(fruits[left]); ++left;break; } ++left; } } ++numAdded[fruits[right]]; } return max(resLenth,right - left); } };
法二宫水三叶:不使用unordered_map,使用vector
class Solution { public: int totalFruit(vector<int>& fruits) { int size = fruits.size(),resLenth = 0; vector<int> numAdded(size); for(int right = 0,left = 0,typeCount = 0;right < size;++right){ ++numAdded[fruits[right]]; if(numAdded[fruits[right]] == 1) ++typeCount;//用typeCount表示当前加了多少个种类 while(typeCount > 2){ --numAdded[fruits[left]]; if(numAdded[fruits[left]] == 0) --typeCount; ++left; } resLenth = max(resLenth,right - left + 1); } return resLenth; } };
标签:right,904,resLenth,fruits,size,成篮,leetcode,numAdded,left From: https://www.cnblogs.com/uacs2024/p/18595835