public class Logger {
private Map<String, Integer> map;
/** Initialize your data structure here. */
public Logger() {
map = new HashMap<String, Integer>();
}
/** 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)) {
int diff = timestamp - map.get(message);
if (diff >= 10) {
map.put(message, timestamp);
return true;
} else {
return false;
}
} else {
map.put(message, timestamp);
return true;
}
}
}
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/
Follow up - what if the input is very large and range is very wide
get rid of older messages
public class Logger {
private class Message {
public int time;
public String msg;
public Message(int t, String m) {
this.time = t;
this.msg = m;
}
}
Queue<Message> queue;
HashSet<String> set;
/** Initialize your data structure here. */
public Logger() {
queue = new LinkedList<>();
set = new HashSet<>();
}
/** 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) {
//get rid of all older messages
while (!queue.isEmpty() && timestamp - queue.peek().time>= 10) {
Message m = queue.poll();
set.remove(m.msg);
}
//check whether the input message is in the set
if (!set.contains(message)) {
queue.offer(new Message(timestamp, message));
set.add(message);
return true;
}
//return
return false;
}
}