[LeetCode] 359. Logger Rate Limiter

日志速率限制器。请你设计一个日志系统,可以流式接收日志以及它的时间戳。该日志会被打印出来,需要满足一个条件:当且仅当日志内容 在过去的 10 秒钟内没有被打印过。给你一条日志的内容和它的时间戳(粒度为秒级),如果这条日志在给定的时间戳应该被打印出来,则返回 true,否则请返回 false。要注意的是,可能会有多条日志在同一时间被系统接收。例子,

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;

思路是用hashmap记录日志内容和时间,每次看到有相同日志进来,则查看一下上一个timestamp是否在10秒钟以内。

Java实现

 1 class Logger {
 2     HashMap<String, Integer> map;
 3     int time;
 4     /** Initialize your data structure here. */
 5     public Logger() {
 6         map = new HashMap<>();
 7     }
 8     
 9     /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
10         If this method returns false, the message will not be printed.
11         The timestamp is in seconds granularity. */
12     public boolean shouldPrintMessage(int timestamp, String message) {
13         if (map.containsKey(message)) {
14             time = map.get(message);
15             if (Math.abs(timestamp - time) < 10) return false;
16         }
17         map.put(message, timestamp);
18         return true;
19     }
20 }
21 
22 /**
23  * Your Logger object will be instantiated and called as such:
24  * Logger obj = new Logger();
25  * boolean param_1 = obj.shouldPrintMessage(timestamp,message);
26  */

JavaScript实现

 1 /**
 2  * Initialize your data structure here.
 3  */
 4 var Logger = function() {
 5     this.map = new Map();
 6 };
 7 
 8 /**
 9  * Returns true if the message should be printed in the given timestamp, otherwise returns false.
10         If this method returns false, the message will not be printed.
11         The timestamp is in seconds granularity. 
12  * @param {number} timestamp 
13  * @param {string} message
14  * @return {boolean}
15  */
16 Logger.prototype.shouldPrintMessage = function(timestamp, message) {
17     return (this.map.has(message) && timestamp - this.map.get(message) < 10) ? false : this.map.set(message, timestamp);
18 };
19 
20 /** 
21  * Your Logger object will be instantiated and called as such:
22  * var obj = new Logger()
23  * var param_1 = obj.shouldPrintMessage(timestamp,message)
24  */

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12695414.html