C++ solution that controls HashMap size


  • 2
    X
    class Logger {
    public:
        /** Initialize your data structure here. */
        Logger() {
            
        }
        
        /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
            If this method returns false, the message will not be printed.
            The timestamp is in seconds granularity. */
        bool shouldPrintMessage(int timestamp, string message) {
            
    	// Remove messages that are older than 10s than the passed-in timestamp
    	for (auto i = myMap.begin(); i != myMap.end();)
    	{
    		auto temp = i; 
    		i++;
    
    		if (temp->second <= timestamp - 10)
    		{
    			myMap.erase(temp);
    		}
    	}
           
            if (myMap.find(message) == myMap.end())
            {
                myMap[message] = timestamp;
                return true;
            }
            
            return false;
        }
        
    private:
    
        unordered_map<string, int> myMap;
    };
    

  • 1
    B

    This is not thread safe.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.