The original title link is here: https://leetcode.com/problems/logger-rate-limiter/
Topic:
Design a logger system this receive stream of messages along with its timestamps, each message should is printed if and on ly if it is not a printed in the last seconds.
Given a message and a timestamp (in seconds granularity), return True if the message should being printed in the Given timest AMP, otherwise returns false.
It is possible this several messages arrive roughly at the same time.
Example:
Logger Logger = new Logger ();//Logging string "foo" at timestamp 1logger.shouldprintmessage (1, "foo"); Returns true; Logging string "Bar" at timestamp 2logger.shouldprintmessage (2, "bar"); Returns true;//logging string "foo" at Timestamp 3logger.shouldprintmessage (3, "foo"); Returns false;//logging string "Bar" at timestamp 8logger.shouldprintmessage (8, "bar"); Returns false;//logging string "foo" at Timestamp 10logger.shouldprintmessage (Ten, "Foo"); Returns false;//logging string "foo" at timestamp 11logger.shouldprintmessage (one, "foo"); Returns true;
Exercises
Seeing the problem again is like returning to the battlefield of that year.
Maintain a hashmap, key is a message, value is the timestamp of the message
The message that is not present is added to HashMap, and return True.
There are no more than 10 message return false.
A message that appears and exceeds 10, with the new HashMap, return True.
Time Complexity:shouldprintmessage O (1).
The size of the space:hashmap.
AC Java:
1 Public classLogger {2 3 /**Initialize your data structure here.*/4Hashmap<string, integer>HM;5 PublicLogger () {6HM =NewHashmap<string, integer>();7 }8 9 /**Returns True if the message should is printed in the given timestamp, otherwise Returns false.Ten If This method returns false, the message won't be printed. One The timestamp is in seconds granularity.*/ A Public BooleanShouldprintmessage (inttimestamp, String message) { - if(!hm.containskey (message)) { - hm.put (message, timestamp); the return true; -}Else if(Timestamp-hm.get (message) < 10){ - return false; -}Else{ + hm.put (message, timestamp); - return true; + } A } at } - - /** - * Your Logger object would be instantiated and called as such: - * Logger obj = new Logger (); - * Boolean param_1 = Obj.shouldprintmessage (timestamp,message); in */
Keep up with design hit Counter
Leetcode Logger Rate Limiter