359. Logger Rate Limiter
Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t
will prevent other identical messages from being printed until timestamp t + 10
).
All messages will come in chronological order. Several messages may arrive at the same timestamp.
Implement the Logger
class:
Logger()
Initializes thelogger
object.bool shouldPrintMessage(int timestamp, string message)
Returnstrue
if themessage
should be printed in the giventimestamp
, otherwise returnsfalse
.
Example 1:
Input ["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"] [[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]] Output [null, true, true, false, false, false, true] Explanation Logger logger = new Logger(); logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11 logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12 logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is // 11 + 10 = 21
1 class Logger { 2 private Map<String, Integer> lookup = new HashMap<>(); 3 /** Initialize your data structure here. */ 4 public Logger() { 5 6 } 7 8 /** Returns true if the message should be printed in the given timestamp, otherwise returns false. 9 If this method returns false, the message will not be printed. 10 The timestamp is in seconds granularity. */ 11 public boolean shouldPrintMessage(int timestamp, String message) { 12 if (lookup.containsKey(message) && (timestamp - lookup.get(message) < 10)) { 13 return false; 14 } 15 16 lookup.put(message, timestamp); 17 18 return true; 19 } 20 } 21 22 public class Logger { 23 public Map<String, Integer> map; 24 int lastSecond = 0; 25 26 /** Initialize your data structure here. */ 27 public Logger() { 28 map = new java.util.LinkedHashMap<String, Integer>(100, 0.6f, true) { 29 protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) { 30 return lastSecond - eldest.getValue() > 10; 31 } 32 }; 33 } 34 35 /** Returns true if the message should be printed in the given timestamp, otherwise returns false. 36 If this method returns false, the message will not be printed. 37 The timestamp is in seconds granularity. */ 38 public boolean shouldPrintMessage(int timestamp, String message) { 39 lastSecond = timestamp; 40 if(!map.containsKey(message)||timestamp - map.get(message) >= 10) { 41 map.put(message,timestamp); 42 return true; 43 } 44 return false; 45 } 46 }