滑动窗口,原来可以通过循环嵌套循环的方式实现。
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
原文地址:https://www.cnblogs.com/lautsie/p/12271637.html
时间: 2024-10-09 18:05:44