[LeetCode] 359. Logger Rate Limiter 记录速率限制器
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 记录速率限制器的更多相关文章
- LeetCode 359. Logger Rate Limiter (记录速率限制器)$
Design a logger system that receive stream of messages along with its timestamps, each message shoul ...
- [LeetCode] Logger Rate Limiter 记录速率限制器
Design a logger system that receive stream of messages along with its timestamps, each message shoul ...
- LeetCode 359 Logger Rate Limiter
Problem: Design a logger system that receive stream of messages along with its timestamps, each mess ...
- 359. Logger Rate Limiter
/* * 359. Logger Rate Limiter * 2016-7-14 by Mingyang * 很简单的HashMap,不详谈 */ class Logger { HashMap< ...
- 【LeetCode】359. Logger Rate Limiter 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcode ...
- [LC] 359. Logger Rate Limiter
Design a logger system that receive stream of messages along with its timestamps, each message shoul ...
- LeetCode Logger Rate Limiter
原题链接在这里:https://leetcode.com/problems/logger-rate-limiter/ 题目: Design a logger system that receive s ...
- Logger Rate Limiter -- LeetCode
Design a logger system that receive stream of messages along with its timestamps, each message shoul ...
- Logger Rate Limiter 十秒限时计数器
[抄题]: Design a logger system that receive stream of messages along with its timestamps, each message ...
随机推荐
- CentOS7安装Postman
1. 进入官网:https://www.getpostman.com/downloads/2. 点击下载3. 直接安装:tar zxvf ***.tar.gz4. 确认当前目录: pwd /home/ ...
- CentOS7卸载 OpenJDK 安装Sun的JDK8
Linux上一般会安装Open JDK,关于OpenJDK和JDK的区别:http://www.cnblogs.com/sxdcgaq8080/p/7487369.html 下面开始安装步骤: --- ...
- 利用avicap32.dll实现的实时视频传输
直接上代码吧! 在窗体上调用的类: using System; using System.Collections.Generic; using System.ComponentModel; using ...
- WM_MOUSEWHEEL、WM_LBUTTONDOWN等父子窗口消息传递陷阱
mfc中,碰到以下问题:父对话框A.子窗口B.B是CWnd对象.需要在B中处理WM_MOUSEWHEEL.WM_LBUTTONDOWN等消息. 所以在B中增加对应的消息处理,发现B中的消息循环中,收不 ...
- idea去除mybatis的xml那个恶心的绿色背景
https://my.oschina.net/qiudaozhang/blog/2877536
- 日期对象|Date构造函数|
var date = new Date(); console.log(date); //Date {Wed Dec 10 2014 15:59:24 GMT+0800} date.getDay() d ...
- Joint Approximative Diagonalization of Eigen matrix (JADE)
特征矩阵联合相似对角化算法[1]. Cardoso于1993年提出的盲信号分离具有代表性的一种算法.是一种基于四阶累积量特征矩阵近似联合对角化盲分离算法.该算法将目标函数最大化问题等价于一组四阶累积量 ...
- 洛谷 P2512 [HAOI2008]糖果传递 题解
每日一题 day47 打卡 Analysis 首先,最终每个小朋友的糖果数量可以计算出来,等于糖果总数除以n,用ave表示. 假设标号为i的小朋友开始有Ai颗糖果,Xi表示第i个小朋友给了第i-1个小 ...
- 2019.12.06 java基础代码
操作系统中默认码表是:gbk (一个中文字符占两个字节): utf-8(一个中文字符占三个字节): 数据库建库时的默认码表是:拉丁码表: (1) public class 定义: ...
- 配置nRF52832 的NFC 专用引脚为 GPIO
nRF52832 是支持NFC的,真可惜本码农没用过. NFC的引脚为 P0.09/P0.10,这两个引脚正常情况下是不能直接当做GPIO来用的,要用的时候,需要在编译环境配置一个宏. 下面是Keil ...