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

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
        
                
                

  

相关文章:

  • 2021-09-30
  • 2022-12-23
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2021-08-13
  • 2021-12-06
猜你喜欢
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案