Number of Recent Calls LeetCode Solution - The Coding Shala
Home >> LeetCode >> Number of Recent Calls
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Number of Recent Calls Problem and will implement its solution in Java.
Number of Recent Calls Problem
You have a RecentCounter class that counts the number of recent requests within a certain time frame.
Implement the RecentCounter class:
- RecentCounter() Initializes the counter with zero recent requests.
- 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 have 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].
- It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
Example 1:
Input:
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output:
[null, 1, 2, 3, 3]
Practice this problem on LeetCode.
LeetCode - Number of Recent Calls Java Solution
Approach 1
Using Queue.
Add new Ping into the queue and remove all the times that don't come in the range t-3000 to t. Return size of the queue.
Java Program:
class RecentCounter { Queue<Integer> queue; public RecentCounter() { queue = new LinkedList<Integer>(); } public int ping(int t) { queue.offer(t); int time = t - queue.peek(); while(time > 3000) { queue.poll(); time = t - queue.peek(); } return queue.size(); } } /** * Your RecentCounter object will be instantiated and called as such: * RecentCounter obj = new RecentCounter(); * int param_1 = obj.ping(t); */
- LeetCode - Find the Difference
- LeetCode - XOR operation in an Array
- LeetCode - Number Complement
- LeetCode - Integer Replacement
- LeetCode - Letter Case Permutation
Comments
Post a Comment