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 ""
相关推荐
Dr.Kun11 分钟前
【鲲码园Python】基于pytorch的鸟品种分类系统(25类)
pytorch·python·分类
是有头发的程序猿31 分钟前
Python爬虫实战:面向对象编程在淘宝商品数据抓取中的应用
开发语言·爬虫·python
萑澈1 小时前
Windows系统Anaconda/Miniconda的安装、配置、基础使用、清理缓存空间和Pycharm/VSCode配置指南
python
Jac_kie_層樓1 小时前
力扣hot100刷题记录(12.2)
算法·leetcode·职场和发展
Onebound_Ed1 小时前
Python爬虫进阶:面向对象设计构建高可维护的1688商品数据采集系统
开发语言·爬虫·python
阿蔹1 小时前
JavaWeb-Selenium 配置以及Selenim classnotfound问题解决
java·软件测试·python·selenium·测试工具·自动化
万粉变现经纪人2 小时前
如何解决 pip install 代理报错 407 Proxy Authentication Required 问题
windows·python·pycharm·beautifulsoup·bug·pandas·pip
李剑一2 小时前
Python学习笔记3
python
luod2 小时前
Python包
python
Mr Lee_2 小时前
Smali 文件生成dex装箱算法整合
开发语言·python·算法