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.
Use hash table to store (message, timestamp). When receiving a message, if it is not in the hash table, return true. If it is in the hash table, but difference between timestamps is larger than 10, return true. Otherwise, return false.
Soultion
Python implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class :
def__init__(self):
"""
Initialize your data structure here.
"""
self.logs = dict()
defshouldPrintMessage(self, timestamp, message):
"""
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.
:type timestamp: int
:type message: str
:rtype: bool
"""
if message notin self.logs or timestamp - self.logs[message] >= 10:
self.logs[message] = timestamp
returnTrue
returnFalse
Java implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class{
/** Initialize your data structure here. */
private Map<String, Integer> logs;
public(){
logs = 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.
近期评论