Skip to content

Commit c8c29af

Browse files
committed
LoggerRateLimiter359
1 parent 7e71dda commit c8c29af

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: src/LoggerRateLimiter359.java

+30
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,36 @@ public boolean shouldPrintMessage(int timestamp, String message) {
5353
}
5454
}
5555

56+
/**
57+
* https://leetcode.com/problems/logger-rate-limiter/discuss/83254/Java-with-a-LinkedHashMap-and-using-removeEldestEntry
58+
*/
59+
class Logger2 {
60+
public Map<String, Integer> map;
61+
int lastSecond = 0;
62+
63+
/** Initialize your data structure here. */
64+
public Logger() {
65+
map = new LinkedHashMap<String, Integer>(100, 0.6f, true) {
66+
protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
67+
return lastSecond - eldest.getValue() > 10;
68+
}
69+
};
70+
}
71+
72+
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
73+
If this method returns false, the message will not be printed.
74+
The timestamp is in seconds granularity. */
75+
public boolean shouldPrintMessage(int timestamp, String message) {
76+
lastSecond = timestamp;
77+
if(!map.containsKey(message)||timestamp - map.get(message) >= 10){
78+
map.put(message,timestamp);
79+
return true;
80+
}
81+
return false;
82+
}
83+
}
84+
85+
5686
/**
5787
* Your Logger object will be instantiated and called as such:
5888
* Logger obj = new Logger();

0 commit comments

Comments
 (0)