美文网首页
359-日志速率限制器

359-日志速率限制器

作者: 饮酒醉回忆 | 来源:发表于2019-07-09 10:34 被阅读0次

    日志速率限制器

    题目

    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秒内没有打印消息时,才应该打印每个消息.

    给定消息和时间戳(以秒为粒度),如果消息应该在给定的时间戳中打印,则返回true,否则返回false.

    有可能几个消息几乎同时到达.

    思路

    其实就是在调用时判断当前的消息是否存在,如果消息存在,判断传入的时间戳是否在原有时间戳之后加10秒之内,如果在10秒内,则返回false,如果不在10秒内,则返回true,并替换.如果在,则返回true.如果消息不存在,则直接存入时间戳加10即可.

    代码

    class Logger{
        Map<String,Integer> shouldPrintMap;
        
        public Logger(){
            shouldPrintMap = new HashMap();
        }
        
        public boolean shouldPrintMessage(int timestamp,String message){
            boolean ans = false;
            if (!map.containsKey(message) || map.get(message) + 10 <= timestamp) {
                ans = true;
                map.put(message, timestamp);
            }
            return ans;
        }
    }
    

    相关文章

      网友评论

          本文标题:359-日志速率限制器

          本文链接:https://www.haomeiwen.com/subject/nbitkctx.html