這題的 maximum number of fruit 指的是 maximum window size,然後因為只有兩個 basket,所以這個 window 裡面只能有兩種 char。所以其實就跟 # 340 - Longest Substring with At Most K Distinct Characters 一樣,只是 k 固定是 2。
正確的解法如下:
classSolution {public:inttotalFruit(vector<int>& tree) {int maxLength =0; unordered_map<int,int> table;int windowStart =0;for(int windowEnd =0; windowEnd<tree.size(); windowEnd++) {table[tree[windowEnd]]++;while(table.size() >2) {if(--table[tree[windowStart]] ==0)table.erase(tree[windowStart]); windowStart++; } // Compare maxLength after assuring there are less // than 2 diff. fruit type maxLength =max(maxLength, windowEnd-windowStart+1); }return maxLength; }};