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(, "foo"); returns true; // logging string "bar" at timestamp 2
logger.shouldPrintMessage(,"bar"); returns true; // logging string "foo" at timestamp 3
logger.shouldPrintMessage(,"foo"); returns false; // logging string "bar" at timestamp 8
logger.shouldPrintMessage(,"bar"); returns false; // logging string "foo" at timestamp 10
logger.shouldPrintMessage(,"foo"); returns false; // logging string "foo" at timestamp 11
logger.shouldPrintMessage(,"foo"); returns true;

思路:用队列来记录当前的所有消息,用一个set来记录哪些消息在这个队列中。

 class Message {
public:
int timestamp;
string msg;
Message(int ts, string m) : timestamp(ts), msg(m) {}
};
class Logger {
public:
/** Initialize your data structure here. */
queue<Message> logQueue;
unordered_set<string> msgInQueue;
Logger() { } /** 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. */
bool shouldPrintMessage(int timestamp, string message) {
//remove all msgs before 10s ago
while (!logQueue.empty() && logQueue.front().timestamp + <= timestamp) {
msgInQueue.erase(logQueue.front().msg);
logQueue.pop();
}
bool notInQueue = msgInQueue.count(message) == ;
//this msg will be printed, add it to log
if (notInQueue) {
logQueue.push(Message(timestamp, message));
msgInQueue.insert(message);
}
return notInQueue;
}
}; /**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* bool param_1 = obj.shouldPrintMessage(timestamp,message);
*/

最新文章

  1. Css样式表【边界边框】【列表方块】
  2. FineUI Grid控件高度自适应
  3. java并发编程系列
  4. 不用找了,比较全的signalR例子已经为你准备好了.
  5. Java习惯用法总结
  6. Oracle基础学习5-- Oracle权限之”角色”
  7. 重写javascript浮点运算
  8. Apache的Mesos和Google的Kubernetes 有什么区别?
  9. IE6/IE7浏览器中&quot;float: right&quot;自动换行的解决方法
  10. mfc动态演示排序算法
  11. Lua“控制”C
  12. [转帖]分布式Unique ID的生成方法一览
  13. JS高级 - 面向对象2(prototype定义)
  14. linux降低内存后oracle数据库无法启动
  15. A Chess Game POJ - 2425
  16. Spring boot返回JSON类型响应及Content-Type设置
  17. POJ 2840
  18. Hadoop主要架构
  19. 深入探讨JS中的数组排序函数sort()和reverse()
  20. 6、数据类型四:sets

热门文章

  1. 前端初学者——初探Modernizr.js Modernizr.js笔记
  2. kafak基本操作
  3. Vue-cli 本地开发请求https 接口 DEPTH_ZERO_SELF_SIGNED_CERT
  4. [译]如何将docker日志重定向到单个文件里
  5. BETA0
  6. 重复造轮子系列--内存池(C语言)
  7. 开头什么的肯定要自我介绍然后把它扔到置顶咯&gt;_&lt;~
  8. 使用Asp.Net Identity 2.0 认证邮箱激活账号(附DEMO)
  9. zepto方法
  10. Extend Html.EditorFor MVC