---
# System prepended metadata

title: 0359. Logger Rate Limiter
tags: [Leetcode, Easy, Google]

---

# 0359. Logger Rate Limiter
###### tags: `Leetcode` `Easy` `Google`
Link: https://leetcode.com/problems/logger-rate-limiter/
## 思路
### 思路一 HashMap $O(1)$ $O(N)$
N是unique message的个数
### 思路二 Two Sets $O(1)$ $O(M)$
M is maximum number of unique message that will be received in a 20 second period.

$lastest$ record the start time of the $newMsg$.
$newMsg$ keeps the messages of $[lastest, lastest +10)$;
$oldMsg$ keeps messages at most 20 seconds before.
## Code
### 思路一 HashMap
```java=
class Logger {
    Map<String, Integer> record;
    
    public Logger() {
        record = new HashMap<>();    
    }
    
    public boolean shouldPrintMessage(int timestamp, String message) {
        if(record.getOrDefault(message, -11)+10<=timestamp){
            record.put(message, timestamp);
            return true;
        }
        return false;
    }
}
```
### 思路二 Two Sets
```java=
class Logger {
    Map<String, Integer> oldMsg;
    Map<String, Integer> newMsg;
    int lastest = -21;
    
    public Logger() {
        oldMsg = new HashMap<>();  
        newMsg = new HashMap<>();
    }
    
    public boolean shouldPrintMessage(int timestamp, String message) {
        if(timestamp>=lastest+20){
            oldMsg.clear();
            newMsg.clear();
            lastest = timestamp;
        }
        else if(timestamp>=lastest+10){
            oldMsg = new HashMap<>(newMsg);
            newMsg.clear();
            lastest = timestamp;
        }
        if(newMsg.containsKey(message)) return false;
        if(oldMsg.containsKey(message) && oldMsg.get(message)+10>timestamp) return false;
        newMsg.put(message, timestamp);
        return true;
    }
}
```