[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 ...
随机推荐
- HDU1395 2^x mod n = 1——积与余数的性质
对于数论的学习比较的碎片化,所以开了一篇随笔来记录一下学习中遇到的一些坑,主要通过题目来讲解 本题围绕:积与余数 HDU1395 2^x mod n = 1 题目描述 输入一个数n,如果存在2的x次方 ...
- Unity进阶:行为树 01
版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...
- 摘:J2EE开发环境搭建(1)——安装JDK、Tomcat、Eclipse
J2EE开发环境搭建(1)——安装JDK.Tomcat.Eclipse 1:背景 进公司用SSH(Struts,spring和hibernate)开发已经有两个月了,但由于一 直要么只负责表示层的开发 ...
- golang gomobile 环境搭建
1. 安装Go语言SDK https://www.golangtc.com/download 2. 配置系统变量这建立GOROOT和GOPATH两个目录,分别对应sdk所在目录与项目文件根目录 3. ...
- Yarn (转自之乎者也)
作者:青俞链接:https://www.zhihu.com/question/34016617/answer/57822812来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出 ...
- SQL操作Spark SQL--BasicSQLTestt
object BasicSQLTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() .a ...
- 读取txt写入excel
import csv #实现的思想:首先从txt中读取所有的内容,NUM=1当做键,其他当做值,如果查找缺少a,b,c,d,e,f,g# 则NUM不会添加到字典中,然后通过所有的NUM和字典中的KEY ...
- JavaScript Array 對象
JavaScript array 對象 array對象,是用於在單個變量中存儲多個值的一種變量類型. 創建array對象的語法: new array(); new array(size); new a ...
- LeetCode 877. Stone Game
原题链接在这里:https://leetcode.com/problems/stone-game/ 题目: Alex and Lee play a game with piles of stones. ...
- 在WinDbg里使用MEX调试扩展
简介 针对WinDbg的MEX调试扩展可以帮助您简化常见的调试器任务,并为调试器提供强大的文本筛选功能.此扩展被Microsoft支持工程师广泛用于解决流程应用程序的故障. 下载&安装 下载m ...