359. Logger Rate Limiter

LeetCode easy original: C# #csharp #design #easy #hash-table #leetcode #string
Văn bản bài toán được dịch từ tiếng Nga theo ngôn ngữ giao diện. Mã không thay đổi.

Создайте систему логирования, которая получает поток сообщений вместе с их временными метками. Каждое уникальное сообщение должно печататься не чаще, чем раз в 10 секунд (то есть, сообщение, напечатанное во временной метке t, предотвратит печать других идентичных сообщений до временной метки t + 10).

Все сообщения будут приходить в хронологическом порядке. Несколько сообщений могут поступить в одно и то же время.

Реализуйте класс Logger:

Logger() Инициализирует объект логгера.

bool shouldPrintMessage(int timestamp, string message) returns true, если сообщение должно быть напечатано в данной временной метке, в противном случае returns false.

Ví dụ:

Input

["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]

[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]

Output

[null, true, true, false, false, false, true]

Explanation

Logger logger = new Logger();

logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11

logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12

logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false

logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false

logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false

logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is 11 + 10 = 21

C# lời giải

đã khớp/gốc
using System;
using System.Collections.Generic;
public class Logger {
    private Dictionary<string, int> msgDict;
    public Logger() {
        msgDict = new Dictionary<string, int>();
    }
    public bool ShouldPrintMessage(int timestamp, string message) {
        if (!msgDict.ContainsKey(message) || timestamp - msgDict[message] >= 10) {
            msgDict[message] = timestamp;
            return true;
        }
        return false;
    }
}

C++ lời giải

bản nháp tự động, xem lại trước khi gửi
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class Logger {
    private unordered_map<string, int> msgDict;
    public Logger() {
        msgDict = new unordered_map<string, int>();
    }
    public bool ShouldPrintMessage(int timestamp, string message) {
        if (!msgDict.count(message) || timestamp - msgDict[message] >= 10) {
            msgDict[message] = timestamp;
            return true;
        }
        return false;
    }
}

Java lời giải

đã khớp/gốc
class Logger {
  private HashMap<String, Integer> msgDict;

  public Logger() {
    msgDict = new HashMap<String, Integer>();
  }

  public boolean shouldPrintMessage(int timestamp, String message) {

    if (!this.msgDict.containsKey(message)) {
      this.msgDict.put(message, timestamp);
      return true;
    }

    Integer oldTimestamp = this.msgDict.get(message);
    if (timestamp - oldTimestamp >= 10) {
      this.msgDict.put(message, timestamp);
      return true;
    } else
      return false;
  }
}

JavaScript lời giải

đã khớp/gốc
class Logger {
    constructor() {
        this.msgDict = new Map();
    }

    shouldPrintMessage(timestamp, message) {
        if (!this.msgDict.has(message) || timestamp - this.msgDict.get(message) >= 10) {
            this.msgDict.set(message, timestamp);
            return true;
        }
        return false;
    }
}

Python lời giải

đã khớp/gốc
class Logger:
    def __init__(self):
        self.msg_dict = {}

    def should_print_message(self, timestamp: int, message: str) -> bool:
        if message not in self.msg_dict or timestamp - self.msg_dict[message] >= 10:
            self.msg_dict[message] = timestamp
            return True
        return False

Go lời giải

đã khớp/gốc
type Logger struct {
    msgDict map[string]int
}

func Constructor() Logger {
    return Logger{msgDict: make(map[string]int)}
}

func (this *Logger) ShouldPrintMessage(timestamp int, message string) bool {
    if oldTimestamp, exists := this.msgDict[message]; !exists || timestamp-oldTimestamp >= 10 {
        this.msgDict[message] = timestamp
        return true
    }
    return false
}

Algorithm

Инициализируем хеш-таблицу/словарь для хранения сообщений вместе с временной меткой.

При поступлении нового сообщения оно может быть напечатано при выполнении одного из следующих условий: Мы никогда раньше не видели это сообщение. Мы видели это сообщение ранее, и оно было напечатано более 10 секунд назад.

В обоих случаях обновляем запись, связанную с сообщением в хеш-таблице, с последней временной меткой.

😎

Vacancies for this task

việc làm đang hoạt động with overlapping task tags are đã hiển thị.

Tất cả việc làm
Chưa có việc làm đang hoạt động.