Skip to content
This repository was archived by the owner on Apr 20, 2024. It is now read-only.

Commit 624fef4

Browse files
committed
added problem-27
1 parent 8fe6ade commit 624fef4

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

problem27/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# 933. Number of Recent Calls
2+
3+
You have a RecentCounter class which counts the number of recent requests within a certain time frame.
4+
5+
Implement the RecentCounter class:
6+
7+
RecentCounter() Initializes the counter with zero recent requests.
8+
int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
9+
It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
10+
11+
12+
## Example 1:
13+
14+
Input:
15+
["RecentCounter", "ping", "ping", "ping", "ping"]
16+
[[], [1], [100], [3001], [3002]]
17+
Output:
18+
[null, 1, 2, 3, 3]
19+
20+
Explanation
21+
RecentCounter recentCounter = new RecentCounter();
22+
recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1
23+
recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2
24+
recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3
25+
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3
26+
27+
28+
## Constraints:
29+
30+
1 <= t <= 109
31+
Each test case will call ping with strictly increasing values of t.
32+
At most 104 calls will be made to ping.

problem27/Solution.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class RecentCounter {
2+
Queue<Integer> queue;
3+
public RecentCounter() {
4+
queue = new LinkedList<>();
5+
}
6+
7+
public int ping(int t) {
8+
if (queue.size() == 0) {
9+
queue.add(t);
10+
return 1;
11+
} else {
12+
if (t <= 3000)
13+
queue.add(t);
14+
else {
15+
int margin = t - 3000;
16+
while (!queue.isEmpty() && queue.peek() < margin)
17+
queue.poll();
18+
queue.add(t);
19+
}
20+
return queue.size();
21+
}
22+
}
23+
}
24+
25+
/**
26+
* Your RecentCounter object will be instantiated and called as such:
27+
* RecentCounter obj = new RecentCounter();
28+
* int param_1 = obj.ping(t);
29+
*/

0 commit comments

Comments
 (0)