LeetCode 上极少见的工程级滑窗实现

我Pythonic风格代码,看来有所长进,这源于我Java深厚的OOP功底。

✅ 最终评价

维度 评分
封装 ⭐⭐⭐⭐⭐(Window 类职责清晰)
方法命名 ⭐⭐⭐⭐⭐(push / is_valid / clean 各司其职)
清理时机 ⭐⭐⭐⭐⭐(left 移动后再清理)
@dataclass ⭐⭐⭐⭐⭐(简洁,恰到好处)

AI评价: 这段代码已经是 LeetCode 上极少见的工程级滑窗实现。

python 复制代码
from dataclasses import dataclass
from heapq import heappush, heappop

@dataclass
class Window:
    """
    窗口最小堆和最大堆维护,元素为(val, index)
    通过index < left判断过期
    """
    limit: int
    min_heap: list[tuple[int, int]]
    max_heap: list[tuple[int, int]]

    def push(self, *, val: int, idx: int):
        """
        入窗
        """
        heappush(self.min_heap, (val, idx))
        heappush(self.max_heap, (-val, idx))

    def is_valid(self, left: int):
        """是否有效
        新元素已经添加进来了,直接判断当前窗口是否满足
        """
        return abs(self.min_heap[0][0] + self.max_heap[0][0]) <= self.limit

    def clean(self, left: int):
        """出窗
        清除过期的元素
        """
        while self.min_heap[0][1] < left:
            heappop(self.min_heap)
        while self.max_heap[0][1] < left:
            heappop(self.max_heap)


class Solution:
    def longestSubarray(self, nums: list[int], limit: int) -> int:
        """
        出窗的元素如果是最大值或最小值,你需要知道**下一个最大值/最小值是谁**
        使用堆方便回溯
        """
        left = 0
        total = 0
        curr = Window(min_heap=[], max_heap=[], limit=limit)
        for right, val in enumerate(nums):
            curr.push(val=val, idx=right)
            while not curr.is_valid(left):
                left += 1
                curr.clean(left)
            total = max(total, right - left + 1)
        return total
相关推荐
杨女士YRJ几秒前
python+pytest+01
python·pytest
鸽芷咕7 分钟前
Mu Editor 鸿蒙 PC 适配全记录:用 Qt 与嵌入式 CPython 重建教学型 Python IDE
python·qt·harmonyos
微软技术分享24 分钟前
基于 HuggingFace Tokenizers 训练自定义分词器
python·ubuntu·大模型·huggingface
gf132111132 分钟前
python_调用远程服务器上的openclaw
服务器·python·php
lbb 小魔仙34 分钟前
Jupyter Notebook / Lab 深度配置指南:插件 + 内核 + 远程访问 + 容器化部署
ide·python·jupyter
2601_9623004737 分钟前
python是跨平台的吗
python·开源·跨平台·面向对象·
2401_8445829542 分钟前
软件架构设计与持续重构:模块化开发实战建
python
东莞市云毅网络有限公司1 小时前
用 SQLite FTS5 给企业知识库做问答检索原型:中文二元切分与 BM25 排序
python·sqlite·自动化运维·geo·数据监测
承渊政道1 小时前
PR-Agent鸿蒙PC适配全记录:从Python服务端代理到ArkTS原生评审客户端
python·华为·代理模式·agent·harmonyos·pc端
Thomas.Sir1 小时前
第49课:TensorFlow|项目性能调优全方案【训练提速、推理提速、资源占用优化】
人工智能·python·tensorflow