[leetcode]Fruit Into Baskets

滑动窗口,原来可以通过循环嵌套循环的方式实现。

class Solution:
    def totalFruit(self, tree: List[int]) -> int:

        result = 0
        fruitDict = {}
        i = 0
        # assert i <= j
        for j in range(len(tree)):
            x = tree[j]
            if x not in fruitDict:
                fruitDict[x] = 0
            fruitDict[x] += 1
            while len(fruitDict) == 3:
                fruitDict[tree[i]] -= 1
                if fruitDict[tree[i]] == 0:
                    del fruitDict[tree[i]]
                i += 1
            result = max(result, j - i + 1)

        return result
        
                
                

  

posted @ 2020-02-07 00:01  阿牧遥  阅读(173)  评论(0编辑  收藏  举报