432. All O`one Data Structure (Hard) - TengnanYao/daily_leetcode GitHub Wiki

class AllOne(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.h = {}

    def inc(self, key):
        """
        Inserts a new key <Key> with value 1. Or increments an existing key by 1.
        :type key: str
        :rtype: None
        """
        self.h[key] = self.h.get(key, 0) + 1
            
    def dec(self, key):
        """
        Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
        :type key: str
        :rtype: None
        """
        self.h[key] -= 1
        if not self.h[key]:
            del self.h[key]

    def getMaxKey(self):
        """
        Returns one of the keys with maximal value.
        :rtype: str
        """
        if not self.h:
            return ""
        m = max(self.h.values())
        for k, v in self.h.items():
            if v == m:
                return k

    def getMinKey(self):
        """
        Returns one of the keys with Minimal value.
        :rtype: str
        """
        if not self.h:
            return ""
        n = min(self.h.values())
        for k, v in self.h.items():
            if v == n:
                return k
        
# 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()
⚠️ **GitHub.com Fallback** ⚠️