Java solution in HashMap

  • 0
        public class Logger {
    //Use HashMap to store the message string and its timestamp as the value. When the hashmap do not have the message, just return true and insert it into the hashmap. If it has the message, if timestamp - value >= 10 return true and replace the original value corresponded to that message. Else just return false
        HashMap<String, Integer> map;
        /** Initialize your data structure here. */
        public Logger() {
            map = 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 (!map.containsKey(message) || (timestamp - map.get(message)) >= 10) {
                map.put(message, timestamp);
                return true;
            } else {
                return false;

  • 0

    @qixu Won't the HashMap grow arbitrarily large as new messages come in?

Log in to reply

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