Java solution


  • 0

    This is my initial solution. Using messages as keys,

    public class Logger {
    
        private Map<String, Integer> table;
        /** Initialize your data structure here. */
        public Logger() {
            table = new HashMap<String, Integer>();
        }
        
        /** 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(int timestamp, String message) {
            if(!table.containsKey(message)) {
                table.put(message, timestamp);
                return true;
            }
            if(table.get(message) <= timestamp - 10) {
                table.put(message, timestamp);
                return true;
            }
            return false;
        }
    }
    

    However there is an another solution to avoid the excessive accumulation of least recent printed messages. Check this out:
    https://discuss.leetcode.com/topic/48615/a-solution-that-only-keeps-part-of-the-messages/3


Log in to reply
 

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