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
相关推荐
TomEval1 小时前
【测AI】第26篇:线上模型监控与告警体系 — 测试不是终点
人工智能·python·功能测试·ai
prince_zxill2 小时前
PEP 751 pylock.toml 实测:pip 26.3 装 6 个包版本全钉死,但 [web] 选不中任何东西
python·pip·依赖管理·pep 751
Thanks_ks4 小时前
Python 的垃圾回收——引用计数撑起日常,分代回收收拾残局
python·内存管理·垃圾回收·循环引用·引用计数·gc 模块·weakref
CyrusYiVPP4 小时前
实测 uv 0.13.7:同一套包,pip 装 94 秒,它只用 19 秒
人工智能·python
yiangL_4 小时前
Python 学习笔记:递归、turtle绘图、字符串与函数
笔记·python·学习
ashiho5 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
lula8885 小时前
PVC-U、PVC-C、PVC-O 差一个字母,差的是三种增强路线
python
数字工作台6 小时前
给 LangGraph 加一道可审计记忆:替换默认 Checkpointer,实现防篡改 + 崩溃不丢数据
python·agent
DKPT7 小时前
Python 的 Web 框架:选型选错的人,都踩了同一个坑
python
2401_868534787 小时前
逻辑网络设计
网络·python