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.

Example:

Logger logger = new Logger();

// logging string "foo" at timestamp 1
logger.shouldPrintMessage(1, "foo"); returns true;

// logging string "bar" at timestamp 2
logger.shouldPrintMessage(2,"bar"); returns true;

// logging string "foo" at timestamp 3
logger.shouldPrintMessage(3,"foo"); returns false;

// logging string "bar" at timestamp 8
logger.shouldPrintMessage(8,"bar"); returns false;

// logging string "foo" at timestamp 10
logger.shouldPrintMessage(10,"foo"); returns false;

// logging string "foo" at timestamp 11
logger.shouldPrintMessage(11,"foo"); returns true;

设计一个记录系统每次接受信息并保存时间戳,然后让我们打印出该消息,前提是最近10秒内没有打印出这个消息。Uber家

解法:哈希表,建立message和timestamp之间映射,如果接收到的消息不在哈希表里,就添加到哈希表里,并返回true。如果已经存在,如果当前时间戳是否比哈希表中保存的时间戳大10秒,则更新哈希表,并返回true,否则返回false。

Java:

public class Logger{

    HashMap<String, Integer> record;

    /** Initialize your data structure here. */
public Logger() {
record= new HashMap<String, Integer>();
} /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity. */
public boolean shouldPrintMessage(int timestamp, String message) {
/* if(record.containsKey(message)){
if( timestamp-record.get(message) >=10){
record.put(message, timestamp);
return true;
}
else{
return false;
} }
else{
record.put(message, timestamp);
return true;
}*/ // 以上是非常连贯的逻辑,一步步做判断,下面是 精简后的判断条件,所以速度上快很多,但是如果没写出上面的代码,没看到重复出现的那两行,可能也不会想到下面的写法 if(record.containsKey(message) && timestamp-record.get(message)<10 ){
return false;
}
else{
record.put(message, timestamp);
return true;
} }
} /**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/  

Python:

# Time:  O(1), amortized
# Space: O(k), k is the max number of printed messages in last 10 seconds
import collections class Logger(object): def __init__(self):
"""
Initialize your data structure here.
"""
self.__dq = collections.deque()
self.__printed = set() def shouldPrintMessage(self, timestamp, message):
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity.
:type timestamp: int
:type message: str
:rtype: bool
"""
while self.__dq and self.__dq[0][0] <= timestamp - 10:
self.__printed.remove(self.__dq.popleft()[1])
if message in self.__printed:
return False
self.__dq.append((timestamp, message))
self.__printed.add(message)
return True # Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)  

C++:

class Logger {
public:
Logger() {} bool shouldPrintMessage(int timestamp, string message) {
if (!m.count(message)) {
m[message] = timestamp;
return true;
}
if (timestamp - m[message] >= 10) {
m[message] = timestamp;
return true;
}
return false;
} private:
unordered_map<string, int> m;
};

C++:

class Logger {
public:
Logger() {} bool shouldPrintMessage(int timestamp, string message) {
if (timestamp < m[message]) return false;
m[message] = timestamp + 10;
return true;
} private:
unordered_map<string, int> m;
};

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 359. Logger Rate Limiter 记录速率限制器的更多相关文章

  1. LeetCode 359. Logger Rate Limiter (记录速率限制器)$

    Design a logger system that receive stream of messages along with its timestamps, each message shoul ...

  2. [LeetCode] Logger Rate Limiter 记录速率限制器

    Design a logger system that receive stream of messages along with its timestamps, each message shoul ...

  3. LeetCode 359 Logger Rate Limiter

    Problem: Design a logger system that receive stream of messages along with its timestamps, each mess ...

  4. 359. Logger Rate Limiter

    /* * 359. Logger Rate Limiter * 2016-7-14 by Mingyang * 很简单的HashMap,不详谈 */ class Logger { HashMap< ...

  5. 【LeetCode】359. Logger Rate Limiter 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcode ...

  6. [LC] 359. Logger Rate Limiter

    Design a logger system that receive stream of messages along with its timestamps, each message shoul ...

  7. LeetCode Logger Rate Limiter

    原题链接在这里:https://leetcode.com/problems/logger-rate-limiter/ 题目: Design a logger system that receive s ...

  8. Logger Rate Limiter -- LeetCode

    Design a logger system that receive stream of messages along with its timestamps, each message shoul ...

  9. Logger Rate Limiter 十秒限时计数器

    [抄题]: Design a logger system that receive stream of messages along with its timestamps, each message ...

随机推荐

  1. netstat -an unix socket 会阻塞吗

    [lyd@localhost ~]$ netstat -an | grep "SOFO"unix 2 [ ACC ] SEQPACKET LISTENING 86308 @*MY- ...

  2. T-sql 遍历结果集

    DECLARE @TAB TABLE( [科室编号] [varchar](50) NULL, [科室编码] [varchar](50) NULL, [科室名称] [varchar](50) NULL, ...

  3. LeetCode 1093. Statistics from a Large Sample

    原题链接在这里:https://leetcode.com/problems/statistics-from-a-large-sample/ 题目: We sampled integers betwee ...

  4. 关于windbg报错"No symbols for ntdll. Cannot continue."问题

    最近我写个例子程序研究下某个异常情况,故意制造了个崩溃.然后分析dmp文件. 当我执行!address -summary命令想观察下进程当前内存情况时,去报如下错误: 0:000> !addre ...

  5. graphql-inspector graphql schema比较&&文档校验&&查找破坏性变动工具

    graphql-inspector 是一个方便的graphql 周边工具,可以加速graphql 应该的开发,同时可以帮助我们排查问题 包含以下特性: 进行schema 的比较 文档校验(通过sche ...

  6. 12-ESP8266 SDK开发基础入门篇--PWM,呼吸灯

    https://www.cnblogs.com/yangfengwu/p/11094085.html PWM其实没有什么,就是看着官方给的API,,,然后就是用呗 对了,其实对于RTOS SDK版本的 ...

  7. 【loj3119】【CTS2019】随机立方体

    题目 ​ 一个 $ n m l $ 的立方体等概率填入 $ 1-nml $ ; ​ 定义一个位置是极大的当且仅当这个位置比三位坐标的至少一维与之相等的位置的值都大. ​ 询问极大值恰好有\(k\)个的 ...

  8. [转]gulp排除已压缩文件思路

    文章转载至[gulp排除已压缩文件思路] gulp默认排除语法的弊端 有个时候我们需要时用gulp排除已经压缩过的js,css等.如果以压缩文件是以".min.js"之类命名规范的 ...

  9. 前端微信小程序云开发基础讲解

    什么是云开发 云开发与传统模式的对比 云开发能力介绍云开发对小程序开发的变革 云开发是微信团队联合腾讯云提供的原生serverless云服务,致力于帮助更多的开发者快速实现小程序业务的开发,快速迭代. ...

  10. App数据指标

    App数据指标 1 App数据指标 2 参考资料 超详细的APP数据指标体系分析