C++ unordered_map solution, no need to call find() before inserting new log message entries, just insert()


  • 0
    K

    To reduce the number of lookups in the unordered_map just call insert() directly without calling find() first. If the key already exists in the container the insert would fail; otherwise you will get the iterator points to the newly inserted entry. It is much more efficient than calling find() and then insert() which requires two lookups.

    class Logger {
    public:
        std::unordered_map<std::string, int> record;
        
        /** 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) {
            auto it = record.insert(std::make_pair(message, timestamp));
            if (!it.second)
            {
                // insert fails, the map stays unchanged. check if we 
                // need to print again
                if ( (timestamp - it.first->second) >= 10)
                {
                    // update the time stamp
                    it.first->second = timestamp;
                    return true;
                }
                else
                {
                    // no, its not time yet
                    return false;
                }
            }
            // insert succeeded, print the message
            return true;
        }
    };
    

Log in to reply
 

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