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;

Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.

这道题让我们设计一个记录系统每次接受信息并保存时间戳,然后让我们打印出该消息,前提是最近10秒内没有打印出这个消息。这不是一道难题,我们可以用哈希表来做,建立消息和时间戳之间的映射,如果某个消息不再哈希表表,我们建立其和时间戳的映射,并返回true。如果应经在哈希表里了,我们看当前时间戳是否比哈希表中保存的时间戳大10,如果是,更新哈希表,并返回true,反之返回false,参见代码如下:

解法一:

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

我们还可以写的更精简一些,如下所示:

解法二:

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

参考资料:

https://leetcode.com/discuss/108703/short-c-java-python-bit-different

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. ajaxFileupload多文件上传
  2. RadioGroup实现导航栏
  3. 【转】一个新的UIButtonMessage 给NGUI,使用委托,自动选择Receiver提供的方法
  4. 简单的oracle分页语句
  5. Spring Batch学习笔记三:JobRepository
  6. Windows 10 自动升级画面
  7. android 导入自己的生成的jar,老是 could not find class
  8. 推荐几个对Asp.Net开发者比较实用的工具 2
  9. django-filter 使用Filter来筛选你的数据
  10. 0118——UIButtton
  11. java web项目基础
  12. JS电子文档链接
  13. thinkPHP 模板中的语法
  14. ajaxfileupload批量上传文件+图片尺寸限制
  15. yii2.0 路由美化以及自定义设置
  16. JavaScript获取元素CSS计算后的样式
  17. Maven 在新版eclipse报错的解决
  18. (转) AdversarialNetsPapers
  19. sql中case when语句的使用
  20. app的描述-软件的描述

热门文章

  1. 【分布式】Zookeeper与Paxos
  2. Django admin美化插件suit应用[原创]
  3. 前端开发:css基础知识之盒模型以及浮动布局。
  4. mvc过滤器学习(1)
  5. springboot 学习资源推荐
  6. Effective java笔记(一),创建与销毁对象
  7. VS2010中dumpbin工具的使用
  8. java多线程解读一(基础篇)
  9. js 隐式转换
  10. js url.slice(star,end) url.lastIndexOf(&#39;/&#39;) + 1, -4