classNode:def__init__(self,key='',cnt=0):self.prev=Noneself.next=Noneself.cnt=cntself.keys={key}definsert(self,node):node.prev=selfnode.next=self.nextnode.prev.next=nodenode.next.prev=nodereturnnodedefremove(self):self.prev.next=self.nextself.next.prev=self.prevclassAllOne:def__init__(self):self.root=Node()self.root.next=self.rootself.root.prev=self.rootself.nodes={}definc(self,key:str)->None:root,nodes=self.root,self.nodesifkeynotinnodes:ifroot.next==rootorroot.next.cnt>1:nodes[key]=root.insert(Node(key,1))else:root.next.keys.add(key)nodes[key]=root.nextelse:curr=nodes[key]next=curr.nextifnext==rootornext.cnt>curr.cnt+1:nodes[key]=curr.insert(Node(key,curr.cnt+1))else:next.keys.add(key)nodes[key]=nextcurr.keys.discard(key)ifnotcurr.keys:curr.remove()defdec(self,key:str)->None:root,nodes=self.root,self.nodescurr=nodes[key]ifcurr.cnt==1:nodes.pop(key)else:prev=curr.previfprev==rootorprev.cnt<curr.cnt-1:nodes[key]=prev.insert(Node(key,curr.cnt-1))else:prev.keys.add(key)nodes[key]=prevcurr.keys.discard(key)ifnotcurr.keys:curr.remove()defgetMaxKey(self)->str:returnnext(iter(self.root.prev.keys))defgetMinKey(self)->str:returnnext(iter(self.root.next.keys))# Your AllOne object will be instantiated and called as such:# obj = AllOne()# obj.inc(key)# obj.dec(key)# param_3 = obj.getMaxKey()# param_4 = obj.getMinKey()
classAllOne{Noderoot=newNode();Map<String,Node>nodes=newHashMap<>();publicAllOne(){root.next=root;root.prev=root;}publicvoidinc(Stringkey){if(!nodes.containsKey(key)){if(root.next==root||root.next.cnt>1){nodes.put(key,root.insert(newNode(key,1)));}else{root.next.keys.add(key);nodes.put(key,root.next);}}else{Nodecurr=nodes.get(key);Nodenext=curr.next;if(next==root||next.cnt>curr.cnt+1){nodes.put(key,curr.insert(newNode(key,curr.cnt+1)));}else{next.keys.add(key);nodes.put(key,next);}curr.keys.remove(key);if(curr.keys.isEmpty()){curr.remove();}}}publicvoiddec(Stringkey){Nodecurr=nodes.get(key);if(curr.cnt==1){nodes.remove(key);}else{Nodeprev=curr.prev;if(prev==root||prev.cnt<curr.cnt-1){nodes.put(key,prev.insert(newNode(key,curr.cnt-1)));}else{prev.keys.add(key);nodes.put(key,prev);}}curr.keys.remove(key);if(curr.keys.isEmpty()){curr.remove();}}publicStringgetMaxKey(){returnroot.prev.keys.iterator().next();}publicStringgetMinKey(){returnroot.next.keys.iterator().next();}}classNode{Nodeprev;Nodenext;intcnt;Set<String>keys=newHashSet<>();publicNode(){this("",0);}publicNode(Stringkey,intcnt){this.cnt=cnt;keys.add(key);}publicNodeinsert(Nodenode){node.prev=this;node.next=this.next;node.prev.next=node;node.next.prev=node;returnnode;}publicvoidremove(){this.prev.next=this.next;this.next.prev=this.prev;}}/** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * String param_3 = obj.getMaxKey(); * String param_4 = obj.getMinKey(); */