904. Fruit Into Baskets

题解

该题可以参照LeetCode 3,没有重复元素的最长子串。
用hash表存储滑动窗口内的元素和个数,然后控制滑动窗口内的元素为2个。
求出滑动窗口最大值。

代码

  1. class Solution {
  2. public:
  3. int totalFruit(vector<int>& fruits) {
  4. unordered_map<int, int> hash;
  5. int ans = 0;
  6. for (int i = 0, j = 0; i < fruits.size(); i ++) {
  7. hash[fruits[i]] ++;
  8. // cout << hash.size() << endl;
  9. while (hash.size() >= 3) {
  10. hash[fruits[j]] --;
  11. if (hash[fruits[j]] == 0) {
  12. hash.erase(fruits[j]);
  13. }
  14. j ++;
  15. }
  16. ans = max(ans, i - j + 1);
  17. }
  18. return ans;
  19. }
  20. };