参考链接:https://blog.csdn.net/qq_41855420/article/details/92836075
构造一个虚拟的窗口[left, right),当窗口tree[left, right)中的水果种数不多于2时,扩大右边界,此时窗口的大小就是可获取的水果种数,否则窗口中的水果种数超过2,则缩小左边界。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: int totalFruit(vector<int>& tree) { int treeSize = tree.size(), maxRes = 0; int left = 0, right = 0, fruitOne, fruitTwo; while (right < treeSize){ int tempRes = 1; fruitOne = tree[left++]; while (left < treeSize && tree[left] == fruitOne){ ++left; tempRes += 1; } right = left; if (right < treeSize){ fruitTwo = tree[right]; } while (right < treeSize){ if (tree[right] == fruitOne || tree[right] == fruitTwo){ ++right; tempRes += 1; } else { break; } } maxRes = max(maxRes, tempRes); } return maxRes; }
};
|