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
相关推荐
Cthy_hy12 小时前
Python算法竞赛:排列组合核心用法
开发语言·python·算法
C+-C资深大佬13 小时前
在PyCharm中创建虚拟环境的具体步骤是什么?
ide·python·pycharm
Dxy123931021613 小时前
Python Tensor 向量入门:从零理解深度学习的“数据语言“
开发语言·python·深度学习
gf132111114 小时前
python_获取飞书卡片交互和审批任务状态变更事件信息
python
ss27314 小时前
ai编程Trae cn生成图书管理系统(1)
java·数据库·spring boot·python·flask·fastapi
如竟没有火炬14 小时前
寻找峰值——二分
java·开发语言·数据结构·python·算法·散列表
前端与小赵15 小时前
Python 模块导入全解析,从基础语法到循环导入破解
python
费弗里15 小时前
里程碑式更新!Dash 4.2新版本新增websocket型回调
python·dash
J2虾虾15 小时前
Spring AI Alibaba - Structured Output 结构化输出
人工智能·python·spring
RSTJ_162516 小时前
PYTHON+AI LLM DAY SIXTY-FOUR
开发语言·python