日志速率限制器

日志速率限制器
请你设计一个日志系统,可以流式接收消息以及它的时间戳。每条 不重复 的消息最多只能每 10 秒打印一次。也就是说,如果在时间戳 t 打印某条消息,那么相同内容的消息直到时间戳变为 t + 10 之前都不会被打印。

所有消息都按时间顺序发送。多条消息可能到达同一时间戳。

实现 Logger 类:

Logger() 初始化 logger 对象
bool shouldPrintMessage(int timestamp, string message) 如果这条消息 message 在给定的时间戳 timestamp 应该被打印出来,则返回 true ,否则请返回 false 。

示例:

输入:
[“Logger”, “shouldPrintMessage”, “shouldPrintMessage”, “shouldPrintMessage”, “shouldPrintMessage”, “shouldPrintMessage”, “shouldPrintMessage”]
[[], [1, “foo”], [2, “bar”], [3, “foo”], [8, “bar”], [10, “foo”], [11, “foo”]]
输出:
[null, true, true, false, false, false, true]

解释:
Logger logger = new Logger();
logger.shouldPrintMessage(1, “foo”); // 返回 true ,下一次 “foo” 可以打印的时间戳是 1 + 10 = 11
logger.shouldPrintMessage(2, “bar”); // 返回 true ,下一次 “bar” 可以打印的时间戳是 2 + 10 = 12
logger.shouldPrintMessage(3, “foo”); // 3 < 11 ,返回 false
logger.shouldPrintMessage(8, “bar”); // 8 < 12 ,返回 false
logger.shouldPrintMessage(10, “foo”); // 10 < 11 ,返回 false
logger.shouldPrintMessage(11, “foo”); // 11 >= 11 ,返回 true ,下一次 “foo” 可以打印的时间戳是 11 + 10 = 21

class Logger {

unordered_map<string,int> hashmap;

public:
    /** Initialize your data structure here. */
    Logger() {
    }
    /** 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. */
    bool shouldPrintMessage(int timestamp, string message) {
       if(hashmap.count(message)<=0)
       {
           hashmap.insert(make_pair(message,timestamp+10));
           return 1;
       }
       else
        {   
            if(timestamp>=hashmap[message])
           {
            hashmap[message]=timestamp+10;
            return 1;
           }
           else
           {
            return 0;
            }
        }
    }
};

/**
 * Your Logger object will be instantiated and called as such:
 * Logger* obj = new Logger();
 * bool param_1 = obj->shouldPrintMessage(timestamp,message);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值