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. python测试开发django-rest-framework-62.基于类的视图(APIView和View)

    前言 django中编辑视图views.py有两种方式,一种是基于类的实现,另外一种是函数式的实现方式,两种方法都可以用. REST框架提供了一个APIView类,它是Django View类的子类. ...

  2. exception内置对象

    当当前页面可能发生异常的时候,此页面将此异常交给另外一个页面处理 在page处添加    errorPage="处理异常的页面.jsp" 在异常处理的页面的page处应该添加  i ...

  3. LeetCode 845. Longest Mountain in Array

    原题链接在这里:https://leetcode.com/problems/longest-mountain-in-array/ 题目: Let's call any (contiguous) sub ...

  4. python3 爬虫继续爬笔趣阁 ,,,,,,,

    学如逆水行舟,不进则退 今天想看小说..找了半天,没有资源.. 只能自己爬了 想了半天.,,,忘记了这个古老的技能 捡了一下 import requests from bs4 import Beaut ...

  5. js中回调函数,promise 以及 async/await 的对比用法 对比!!!

    在编程项目中,我们常需要用到回调的做法来实现部分功能,那么在js中我们有哪些方法来实现回调的? 方法1:回调函数 首先要定义这个函数,然后才能利用回调函数来调用! login: function (f ...

  6. 树组件——jstree使用

    本文记录的只是我自己当时的代码,每行的注释很清楚了,你自己可以做相应变通 一.使用前提: 1.下载jstree依赖包 2.相关页面引入样式["jstree/themes/default/st ...

  7. Phalcon框架的编译安装 内存不足的解决办法

    对症解决 有两种解决方法,一种是提升ECS系统内存.但是却要真金白银跟阿里云去购买的.另一种,则是手动创建swap交换文件.下面来介绍第二种方法. 第一步:首先确定系统是否已经开启swap交换分区: ...

  8. Codevs 2800 送外卖(状压DP)

    2800 送外卖 时间限制: 2 s 空间限制: 256000 KB 题目等级 : 钻石 Diamond 题目描述 Description 有一个送外卖的,他手上有n份订单,他要把n份东西,分别送达n ...

  9. 将对象转化为数组,并且适用select下拉

    当你做element-ui的select下拉的时候数据是从后台请求,但是怎么才能将obj转成数组呢.并且后台返回的key和value中的key是要传的参数 var obj = { name: 'gab ...

  10. GIT生成SSH-KEY公钥放到服务器免密登录

    在使用git时老是碰到在push的时候提示没有权限的问题,那么现在咱们就来创建ssh-key来免密登录.我们来看看如何配置服务器端的 SSH 访问. 本例中,我们将使用 authorized_keys ...