yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #359. Logger Rate Limiter #277

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class Log {
        public int timestamp;
        public String message;
        public Log(int timestamp, String message) {
            this.timestamp = timestamp;
            this.message = message;
        }
    }

class Logger {
    Queue<Log> queue = new ArrayDeque<>();
    Set<String> dict = new HashSet<>();
    /** Initialize your data structure here. */
    public Logger() {}

    /** 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) {
        while (!queue.isEmpty() && queue.peek().timestamp <= timestamp - 10) {
            Log rm = queue.poll();
            dict.remove(rm.message);
        }

        if (!dict.contains(message)) {
            queue.offer(new Log(timestamp, message));
            dict.add(message);
            return true;
        }
        return false;
    }
}

/**
 * Your Logger object will be instantiated and called as such:
 * Logger obj = new Logger();
 * boolean param_1 = obj.shouldPrintMessage(timestamp,message);
 */