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 };
  • 相关阅读:
    Swift 面向对象解析(二)
    Swift 面向对象解析(一)
    iOS 动画笔记 (二)
    iOS 动画笔记 (一)
    UICollectionView 很简单的写个瀑布流
    MVC校验
    win8.1弹框
    Python开发之pip使用详解
    MySQL基础之数据类型和运算符
    网络爬虫之scrapy爬取某招聘网手机APP发布信息
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6248185.html
Copyright © 2011-2022 走看看