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. scrapy框架爬取开源中国项目大厅所有的发布项目。

    本文爬取的字段,项目名称,发布时间,项目周期,应用领域,最低报价,最高报价,技术类型 1,items中定义爬取字段. import scrapy class KaiyuanzhongguoItem(s ...

  2. 项目笔记---WPF之Metro风格UI(转)

    写在前面 作为新年开篇的文章,当然要选择比较“Cool”的东西来分享,这自然落到了WPF身上,WPF技术自身可塑性非常强,其强大的绘图技术以及XAML技术比WinForm而言有本质的飞跃. 切入正题, ...

  3. Python使用pip安装TensorFlow模块

    1.首先确保已经安装python,然后用pip来安装matplotlib模块. 2.进入到cmd窗口下,建议执行python -m pip install -U pip setuptools进行升级. ...

  4. QT 子文件的建立(pri)

    QT 在做项目的时候有时会有许多不同种类的文件,如果这些文件放在一起会显得特别乱,我们可以将文件用文件夹分类,这样会比较有条理. 1. 在项目文件夹下建立新的文件夹,并在文件夹中添加文本文档将后缀改为 ...

  5. sql null+字符=null

    哦,谢谢你,我还想问一个declare @temp varchar(10),@identity varchar(10),@sura varchar(10),@p int,@len int,@nod1  ...

  6. postgres高可用学习篇三:haproxy+keepalived实现postgres负载均衡

    环境: CentOS Linux release 7.6.1810 (Core) 内核版本:3.10.0-957.10.1.el7.x86_64 node1:192.168.216.130 node2 ...

  7. django-列表分页和排序

    视图函数views.py # 种类id 页码 排序方式 # restful api -> 请求一种资源 # /list?type_id=种类id&page=页码&sort=排序方 ...

  8. Java 锁(学习笔记)

    关于Java 锁的知识整理与回顾(个人笔记): 锁有哪些,分别用来干嘛? Java实现锁有两种方式,synchronized关键字和Lock (1)Lock(可判断锁状态) Lock是基于JDK层面实 ...

  9. AOP_原理

    什么是AOPAOP(Aspect-OrientedProgramming,面向方面编程),可以说是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入封 ...

  10. 关于System.BadImageFormatException

    什么是BadImageFormatException BadImageFormatException是当动态链接库 (DLL) 或可执行程序的文件映像无效时引发的异常. 可能的原因 如果动态链接库 ( ...