Python | Leetcode Python题解之第432题全O(1)的数据结构

题目:

题解:

python 复制代码
class Node:
    def __init__(self, key="", count=0):
        self.prev = None
        self.next = None
        self.keys = {key}
        self.count = count

    def insert(self, node: 'Node') -> 'Node':  # 在 self 后插入 node
        node.prev = self
        node.next = self.next
        node.prev.next = node
        node.next.prev = node
        return node

    def remove(self):  # 从链表中移除 self
        self.prev.next = self.next
        self.next.prev = self.prev

class AllOne:
    def __init__(self):
        self.root = Node()
        self.root.prev = self.root
        self.root.next = self.root  # 初始化链表哨兵,下面判断节点的 next 若为 self.root,则表示 next 为空(prev 同理)
        self.nodes = {}

    def inc(self, key: str) -> None:
        if key not in self.nodes:  # key 不在链表中
            if self.root.next is self.root or self.root.next.count > 1:
                self.nodes[key] = self.root.insert(Node(key, 1))
            else:
                self.root.next.keys.add(key)
                self.nodes[key] = self.root.next
        else:
            cur = self.nodes[key]
            nxt = cur.next
            if nxt is self.root or nxt.count > cur.count + 1:
                self.nodes[key] = cur.insert(Node(key, cur.count + 1))
            else:
                nxt.keys.add(key)
                self.nodes[key] = nxt
            cur.keys.remove(key)
            if len(cur.keys) == 0:
                cur.remove()

    def dec(self, key: str) -> None:
        cur = self.nodes[key]
        if cur.count == 1:  # key 仅出现一次,将其移出 nodes
            del self.nodes[key]
        else:
            pre = cur.prev
            if pre is self.root or pre.count < cur.count - 1:
                self.nodes[key] = cur.prev.insert(Node(key, cur.count - 1))
            else:
                pre.keys.add(key)
                self.nodes[key] = pre
        cur.keys.remove(key)
        if len(cur.keys) == 0:
            cur.remove()

    def getMaxKey(self) -> str:
        return next(iter(self.root.prev.keys)) if self.root.prev is not self.root else ""

    def getMinKey(self) -> str:
        return next(iter(self.root.next.keys)) if self.root.next is not self.root else ""
相关推荐
song854601134几秒前
锁的初步学习
开发语言·python·学习
Dcs13 分钟前
提升 Python 性能的 10 个智能技巧
python
深蓝电商API1 小时前
0 基础入门爬虫:Python+requests 环境搭建保姆级教程
开发语言·爬虫·python
MediaTea1 小时前
Python 第三方库:PyTorch(动态计算图的深度学习框架)
开发语言·人工智能·pytorch·python·深度学习
kyle-fang1 小时前
pytorch-张量转换
人工智能·pytorch·python
Blossom.1181 小时前
AI Agent记忆系统深度实现:从短期记忆到长期人格的演进
人工智能·python·深度学习·算法·决策树·机器学习·copilot
yanxiaoyu1102 小时前
Pycharm远程调用Autodl进行训练(关机后不影响)
ide·python·pycharm
云和数据.ChenGuang2 小时前
Python 3.14 与 PyCharm 2025.2.1 的调试器(PyDev)存在兼容性问题
开发语言·python·pycharm
mortimer2 小时前
从零打造一款桌面实时语音转文字工具:PySide6 与 Sherpa-Onnx 的实践
python·github·pyqt
AnalogElectronic2 小时前
用AI写游戏4——Python实现飞机大战小游戏1
python·游戏·pygame