[LeetCode] 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;
Credits:
Special thanks to @memoryless for adding this problem and creating all test cases.

这道题让我们设计一个记录系统每次接受信息并保存时间戳,然后让我们打印出该消息,前提是最近10秒内没有打印出这个消息。这不是一道难题,我们可以用哈希表来做,建立消息和时间戳之间的映射,如果某个消息不再哈希表表,我们建立其和时间戳的映射,并返回true。如果应经在哈希表里了,我们看当前时间戳是否比哈希表中保存的时间戳大10,如果是,更新哈希表,并返回true,反之返回false,参见代码如下:

解法一:

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;
};

我们还可以写的更精简一些,如下所示:

解法二:

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;
};

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

相关文章
|
存储 前端开发 算法
打败100%的用户LeetCode学生出勤记录使用JavaScript解题|前端学算法
打败100%的用户LeetCode学生出勤记录使用JavaScript解题|前端学算法
100 0
打败100%的用户LeetCode学生出勤记录使用JavaScript解题|前端学算法
【leetcode刷题记录】js-两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
|
数据库
LeetCode(数据库)- Confirmation Rate
LeetCode(数据库)- Confirmation Rate
73 0
|
数据库
LeetCode(数据库)- 报告的记录 II
LeetCode(数据库)- 报告的记录 II
43 0
|
数据库
LeetCode(数据库)- 报告的记录
LeetCode(数据库)- 报告的记录
69 0
|
Java
LeetCode刷题记录(一):两数相加
LeetCode刷题记录(一):两数相加
107 0
|
机器学习/深度学习 缓存
【刷穿 LeetCode】552. 学生出勤记录 II :「记忆化搜索」&「动态规划」&「矩阵快速幂」
【刷穿 LeetCode】552. 学生出勤记录 II :「记忆化搜索」&「动态规划」&「矩阵快速幂」
【刷穿 LeetCode】551. 学生出勤记录 I : 简单模拟题(附模拟题目录)
【刷穿 LeetCode】551. 学生出勤记录 I : 简单模拟题(附模拟题目录)
|
算法 Java C#
【算法千题案例】每日LeetCode打卡——83.学生出勤记录 I
📢前言 🌲原题样例:学生出勤记录 I 🌻C#方法:一次遍历 🌻Java 方法:一次遍历 💬总结
|
算法 Java C#
LeetCode刷题551-简单-学生出勤记录 I
LeetCode刷题551-简单-学生出勤记录 I
187 0
LeetCode刷题551-简单-学生出勤记录 I