Leetcode - 359. Logger Rate Limiter

숲사람·2023년 7월 23일
0

멘타트 훈련

목록 보기
220/237

문제

logging시스템을 구현. string 타입의 메시지와 timestamp가 입력된다. 동일한 메시지를 새로 받으려면 10초 이후에 가능하다. 가령 "foo"라는 메시지가 3초에 도착했었고. 9초에 "foo"가 도착했다면 메시지를 새로 저장할수없다(false가 return). 만약 13초에 도착한다면 새로 받을수 있다(true 리턴).

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

아이디어

  • 메시지에 해당하는 해시테이블을 만들고, 저장에 성공한 timestamp만 테이블에 갱신. 이전에 저장된 timestamp + 10 이상의 timestamp가 들어왔을때만 해시테이블 갱신.

풀이

class Logger {
public:
    unordered_map<std::string, int> map;
    Logger() {
       
    }
    
    bool shouldPrintMessage(int timestamp, string message) {
        if (map.find(message) != map.end()) {
            if (timestamp < map[message] + 10) {
                return false;
            }
        }
        map[message] = timestamp;
        return true;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

1개의 댓글

comment-user-thumbnail
2023년 7월 23일

공감하며 읽었습니다. 좋은 글 감사드립니다.

답글 달기