LeetCode 359 Logger Rate Limiter

Problem:

Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.

Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.

It is possible that several messages arrive roughly at the same time.

Summary:

设计一个日志系统,判断信息流中的信息能否在特定时间发送。每次传入一个字符串以及发送时间,若该字符串在前十秒未发送过,则return true,否则return false,不发送该字符串。

Solution:

1. unordered_map中存入上次某字符串的发送时间。

 1 class Logger {
 2 public:
 3     Logger() {
 4         
 5     }
 6     
 7     bool shouldPrintMessage(int timestamp, string message) {
 8         if (!m.count(message) || timestamp - m[message] >= 10) {
 9             m[message] = timestamp;
10             return true;
11         }
12         else {
13             return false;
14         }
15     }
16 
17 private:
18     unordered_map<string, int> m;
19 };

2. 简便写法:unordered_map存入某字符串下次可发送时间。

 1 class Logger {
 2 public:
 3     Logger() {
 4         
 5     }
 6     
 7     bool shouldPrintMessage(int timestamp, string message) {
 8         if (m[message] > timestamp) {
 9             return false;
10         }
11         
12         m[message] = timestamp + 10;
13         return true;
14     }
15 
16 private:
17     unordered_map<string, int> m;
18 };
原文地址:https://www.cnblogs.com/VickyWang/p/6248185.html