题目描述 用滑动窗口法来解决

class Solution:
    def totalFruit(self, fruits: List[int]) -> int:
        slow = fast = 0
        tree_type = []
        maxnum = 1
        for fast in range(len(fruits)):
            if fruits[fast] in tree_type:
                continue
            else:
                if len(tree_type)<2:
                    tree_type.append(fruits[fast])
                else:
                    maxnum = max(maxnum,fast-slow)
                    slow = fast-2
                    while fruits[slow]==fruits[fast-1]:
                        slow -= 1
                    tree_type.remove(fruits[slow])
                    slow += 1
                    tree_type.append(fruits[fast])
        return max(maxnum,fast-slow+1)

运行结果:

904. Fruit Into Baskets刷题笔记_leetcode