Skip to content

Commit ee54514

Browse files
committed
fd
1 parent b9f7d89 commit ee54514

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-3
lines changed

solution/src/main/java/com/inuker/solution/LoggerRateLimiter.java

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package com.inuker.solution;
22

3+
import java.util.Comparator;
34
import java.util.HashMap;
5+
import java.util.PriorityQueue;
6+
import java.util.Queue;
47

58
/**
69
* Created by liwentian on 2017/8/31.
@@ -15,21 +18,42 @@ public class LoggerRateLimiter {
1518

1619
private HashMap<String, Integer> mMap;
1720

21+
private Queue<String> mQueue;
22+
1823
/** Initialize your data structure here. */
1924
public LoggerRateLimiter() {
2025
mMap = new HashMap<>();
26+
mQueue = new PriorityQueue<>(new Comparator<String>() {
27+
@Override
28+
public int compare(String o1, String o2) {
29+
int time1 = mMap.getOrDefault(o1, -100);
30+
int time2 = mMap.getOrDefault(o2, -100);
31+
return time1 - time2;
32+
}
33+
});
34+
}
35+
36+
private void clearExpired(int timestamp) {
37+
while (!mQueue.isEmpty()) {
38+
String msg = mQueue.peek();
39+
if (timestamp - mMap.get(msg) >= 10) {
40+
mQueue.poll();
41+
mMap.remove(msg);
42+
}
43+
}
2144
}
2245

2346
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
2447
If this method returns false, the message will not be printed.
2548
The timestamp is in seconds granularity. */
2649
public boolean shouldPrintMessage(int timestamp, String message) {
2750
int time = mMap.getOrDefault(message, -100);
51+
boolean ret = false;
2852
if (timestamp - time >= 10) {
2953
mMap.put(message, timestamp);
30-
return true;
31-
} else {
32-
return false;
54+
ret = true;
3355
}
56+
clearExpired(timestamp);
57+
return ret;
3458
}
3559
}

test/src/main/java/com/inuker/test/main.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,26 @@ public class main {
2424
public static void main(String[] args) {
2525

2626
}
27+
28+
class Logger {
29+
30+
HashMap<String, Integer> map = new HashMap<>();
31+
32+
/** Initialize your data structure here. */
33+
public Logger() {
34+
35+
}
36+
37+
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
38+
If this method returns false, the message will not be printed.
39+
The timestamp is in seconds granularity. */
40+
public boolean shouldPrintMessage(int timestamp, String message) {
41+
int time = map.getOrDefault(message, -100);
42+
if (time <= timestamp - 10) {
43+
map.put(message, timestamp);
44+
return true;
45+
}
46+
return false;
47+
}
48+
}
2749
}

0 commit comments

Comments
 (0)