Java, with a LinkedHashMap and using removeEldestEntry


  • 9
    A
    public class Logger {
    
        public Map<String, Integer> map;
        int lastSecond = 0;
        
        /** Initialize your data structure here. */
        public Logger() {
            map = new java.util.LinkedHashMap<String, Integer>(100, 0.6f, true) {
                protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
                    return lastSecond - eldest.getValue() > 10;
                }
            };
        }
        
        /** 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) {
            lastSecond = timestamp;
            if(!map.containsKey(message)||timestamp - map.get(message) >= 10){
                map.put(message,timestamp);
                return true;
            }
            return false;
        }
    }

  • 1
    E

    Thumbs up for the smart usage of LinkedHashMap. Your solution deserves more votes!


  • 0
    T

    @eaglesky Yeah I think this is the natural next question in an interview to build off the first: now add an ejection policy to prevent the hashmap from getting too large.


  • 0
    B
    This post is deleted!

Log in to reply
 

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