1: class Logger {
2: unordered_map<string, int> mp;
3: public:
4: /** Initialize your data structure here. */
5: Logger() {
6: }
7: /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
8: If this method returns false, the message will not be printed.
9: The timestamp is in seconds granularity. */
10: bool shouldPrintMessage(int timestamp, string message) {
11: if (timestamp < mp[message]) return false;
12: mp[message] = timestamp + 10;
13: return true;
14: }
15: };
16: /**
17: * Your Logger object will be instantiated and called as such:
18: * Logger obj = new Logger();
19: * bool param_1 = obj.shouldPrintMessage(timestamp,message);
20: */
Sunday, July 17, 2016
359. Logger Rate Limiter
I was trying to solve it as the same way as "362. Design Hit Counter" did. However, after reading the top rated solutions, I realized this problem is much easier. We can have a hash table whose key is the message and value is the expiration time. Once a new message comes in, we check if the timestamp falls in the expiration time which means the existing message is still valid, i.e. it has been printed in last 10 seconds. In this case, we print false. Otherwise, we update the expiration time.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment