首页 技术 正文
技术 2022年11月10日
0 收藏 328 点赞 3,302 浏览 1678 个字

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 题目讲解汇总(持续更新中…)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295