LeetCode 359. Logger Rate Limiter (记录速率限制器)$
2017-11-07 05:51
316 查看
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;
题目标签:Hash Table
题目让我们设计一个 message 是否可以发送的检测器,只有在这个message 第一次发送,或者 上一次发送已经过去了10秒的情况下,才可以发送。
利用HashMap 来保存 message, 和它的 timestamp 就可以了。
Java Solution:
Runtime beats 49.91%
完成日期:06/06/2017
关键词:HashMap
关键点:保存message 和 timestamp
class Logger { HashMap<String, Integer> map; /** Initialize your data structure here. */ public Logger() { map = new HashMap<>(); } /** 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(!map.containsKey(message)) // first time for this message { map.put(message, timestamp); return true; } else // at least second time for this message { if(timestamp >= map.get(message) + 10) { map.put(message, timestamp); return true; } else return false; } } } /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * boolean param_1 = obj.shouldPrintMessage(timestamp,message); */
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
相关文章推荐
- [LeetCode] Logger Rate Limiter 记录速率限制器
- LeetCode 359. Logger Rate Limiter 记录速率限制器
- [LeetCode] 359. Logger Rate Limiter 记录速率限制器
- [LeetCode刷题记录]190-191 Number of 1 Bits & Reverse Bits
- 个人记录-LeetCode 100. Same Tree
- 个人记录-LeetCode 36. Valid Sudoku
- 【LeetCode刷题记录】Number of 1 Bits
- leetcode记录
- leetcode编程记录19 #47 Permutations II
- 个人记录-LeetCode 16. 3Sum Closest
- leetcode刷题,总结,记录,备忘42
- leetcode刷题。总结,记录,备忘 191
- 个人记录-LeetCode 17. Letter Combinations of a Phone Number
- 个人记录-LeetCode 18. 4Sum
- 个人记录-LeetCode 84. Largest Rectangle in Histogram
- 个人记录-LeetCode 20. Valid Parentheses
- 个人记录-LeetCode 85. Maximal Rectangle
- LeetCode刷题记录5-计算有序数组不同项的个数
- leetcode刷题,总结,记录,备忘 328
- [leetcode] 学习记录——Compare Version Numbers