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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值