【问题标题】:Logger Rate Limiter记录器速率限制器
【发布时间】:2020-08-02 06:18:13
【问题描述】:

设计一个接收消息流及其时间戳的记录器系统,当且仅当在最后 10 秒内未打印每条消息时,才应打印每条消息。

给定一条消息和一个时间戳(以秒为单位),如果消息应该以给定的时间戳打印,则返回 true,否则返回 false。

可能有几条消息大致同时到达

示例: 记录器 logger = new Logger();

// 在时间戳 1 处记录字符串“foo” logger.shouldPrintMessage(1, "foo");返回真;

// 在时间戳 2 处记录字符串“bar” logger.shouldPrintMessage(2,"bar");返回真;

// 在时间戳 3 处记录字符串“foo” logger.shouldPrintMessage(3,"foo");返回假;

// 在时间戳 8 处记录字符串“bar” logger.shouldPrintMessage(8,"bar");返回假;

// 在时间戳 10 处记录字符串“foo” logger.shouldPrintMessage(10,"foo");返回假;

// 在时间戳 11 处记录字符串“foo” logger.shouldPrintMessage(11,"foo");返回真;

请告诉方法和问题。没看懂,谢谢。

【问题讨论】:

  • 看起来像家庭作业。如果你不明白这个练习,最好问你的教练。
  • 使用 HashMap。它会更快。

标签: algorithm


【解决方案1】:

当且仅当在最后 10 秒内未打印每条消息时,才应打印每条消息

这意味着记录器必须跟踪在过去 10 秒(或更长时间)内打印了哪些消息。

这可以通过(例如)消息的链接列表来完成,这样当收到消息时,您会丢弃列表中超过 10 秒的任何消息,然后检查新消息是否与某事相同仍然在列表中,以决定是忽略新消息还是打印新消息并将其添加到列表中。

【讨论】:

  • 非常感谢,我使用散列完成了它,但链表也可以这样做
【解决方案2】:

设计它使用 HashMap 来跟踪时间和消息: 我们检查存储在 hashmap 中的时间是否存在差异 并且当前时间戳小于我们将返回 false 否则我们使用当前时间戳更新哈希图。

解决方法如下:

类记录器{

/** Initialize your data structure here. */
private HashMap<String, Integer> map;
public Logger() {
 map = new HashMap<>();
}

/** 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. */
public boolean shouldPrintMessage(int timestamp, String message) {
    if (!map.containsKey(message)) {
        map.put(message, timestamp);
        return true;
    }
    
    int t1 = map.get(message);
    if (timestamp-t1 < 10) {
        return false;
    }
    map.put(message, timestamp);
    return true;
}

}

/**

  • 您的 Logger 对象将被实例化并按如下方式调用:
  • 记录器 obj = new Logger();
  • boolean param_1 = obj.shouldPrintMessage(timestamp,message); */

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2020-03-25
    • 2017-12-18
    • 2022-11-10
    • 2017-08-20
    • 2022-10-13
    相关资源
    最近更新 更多