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 };
  • 相关阅读:
    linux awk命令详解
    Linux 大页面使用与实现简介(转)
    二层设备与三层设备的区别--总结
    Windows下的cd命令
    linux常用命令
    上班第一天
    linux 内核移植和根文件系统的制作
    Sizeof与Strlen的区别与联系
    嵌入式软件工程师面试题
    SpringBoot简单打包部署(附工程)
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6248185.html
Copyright © 2011-2022 走看看