Using Java HashMap


  • 0
    A
    public class Logger {
    
        private Map<String, Integer> messageTimestamps;
    
        public Logger() {
            messageTimestamps = new HashMap<>();
        }
    
        /** 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. */
        public boolean shouldPrintMessage(final int timestamp, final String message) {
            Integer lastTimestamp = messageTimestamps.getOrDefault(message, null);
            if (lastTimestamp != null && timestamp - lastTimestamp < 10) {
                return false;
            } else {
                lastTimestamp = timestamp;
                messageTimestamps.put(message, lastTimestamp);
                return true;
            }
        }
    }
    

Log in to reply
 

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