zoukankan      html  css  js  c++  java
  • LeetCode 359 Logger Rate Limiter

    Problem:

    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.

    Summary:

    设计一个日志系统,判断信息流中的信息能否在特定时间发送。每次传入一个字符串以及发送时间,若该字符串在前十秒未发送过,则return true,否则return false,不发送该字符串。

    Solution:

    1. unordered_map中存入上次某字符串的发送时间。

     1 class Logger {
     2 public:
     3     Logger() {
     4         
     5     }
     6     
     7     bool shouldPrintMessage(int timestamp, string message) {
     8         if (!m.count(message) || timestamp - m[message] >= 10) {
     9             m[message] = timestamp;
    10             return true;
    11         }
    12         else {
    13             return false;
    14         }
    15     }
    16 
    17 private:
    18     unordered_map<string, int> m;
    19 };

    2. 简便写法:unordered_map存入某字符串下次可发送时间。

     1 class Logger {
     2 public:
     3     Logger() {
     4         
     5     }
     6     
     7     bool shouldPrintMessage(int timestamp, string message) {
     8         if (m[message] > timestamp) {
     9             return false;
    10         }
    11         
    12         m[message] = timestamp + 10;
    13         return true;
    14     }
    15 
    16 private:
    17     unordered_map<string, int> m;
    18 };
  • 相关阅读:
    魔方
    js烟花特效
    面试cookie
    扩展日期插件
    通过javascript实现1~100内能同时被2和3整除的数并生成如下表格
    用三或四个个div标签实现工字效果
    2015_WEB页面前端工程师_远程测题_东方蜘蛛_1
    js公有、私有、静态属性和方法的区别
    Docker libnetwork(CNM)设计简介
    kubernetes,Docker网络相关资料链接
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6248185.html
Copyright © 2011-2022 走看看