Super easy Java HashMap solution


  • 3
    D

    Suggestions are welcome!

    private Map<String, Integer> map;
    
    /** Initialize your data structure here. */
    public Logger() {
        map = new HashMap<>();
    }
    
    /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity. */
    public boolean shouldPrintMessage(int timestamp, String message) {
        if (map.containsKey(message) && (timestamp - map.get(message)) < 10) {
            return false;
        } 
        map.put(message, timestamp);
        return true;
    }

  • 0
    L

    One cosmetic change. You can remove the else condition :) !

    if (map.containsKey(message) && (timestamp - map.get(message)) < 10) {
            return false;
        } 
    map.put(message, timestamp);
    return true;

  • 0
    D

    Thx, removed.


  • 0
    B

    Won't the number of keys in the HashMap grow arbitrarily large as new messages come in?


  • 0
    D

    @bdastous That's possible, but I think it's a separate concern, not related to this particular question.


Log in to reply
 

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