题目:
题解:
class Node:def __init__(self, key="", count=0):self.prev = Noneself.next = Noneself.keys = {key}self.count = countdef insert(self, node: 'Node') -> 'Node': # 在 self 后插入 nodenode.prev = selfnode.next = self.nextnode.prev.next = nodenode.next.prev = nodereturn nodedef remove(self): # 从链表中移除 selfself.prev.next = self.nextself.next.prev = self.prevclass AllOne:def __init__(self):self.root = Node()self.root.prev = self.rootself.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.nextelse:cur = self.nodes[key]nxt = cur.nextif 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] = nxtcur.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 仅出现一次,将其移出 nodesdel self.nodes[key]else:pre = cur.previf 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] = precur.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 ""