首页 > 技术文章 > Leetcode 904. Fruit Into Baskets

zywscq 2019-03-14 21:47 原文

sliding window(滑动窗口)算法

class Solution(object):
    def totalFruit(self, tree):
        """
        :type tree: List[int]
        :rtype: int
        """
        count=collections.Counter()
        left=ans=0
        for i,val in enumerate(tree):
            count[val]+=1
            while (len(count)>=3):
                count[tree[left]]-=1
                if count[tree[left]]==0:
                    del count[tree[left]]
                left+=1
            ans=max(ans,i-left+1)
        return ans     

 

推荐阅读