|
| 1 | +package by.andd3dfx.numeric; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Deque; |
| 5 | + |
| 6 | +/** |
| 7 | + * <pre> |
| 8 | + * <a href="https://leetcode.com/problems/number-of-recent-calls/description/">Task description</a> |
| 9 | + * |
| 10 | + * You have a RecentCounter class which counts the number of recent requests within a certain time frame. |
| 11 | + * |
| 12 | + * Implement the RecentCounter class: |
| 13 | + * - RecentCounter() Initializes the counter with zero recent requests. |
| 14 | + * - int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests |
| 15 | + * that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that |
| 16 | + * have happened in the inclusive range [t - 3000, t]. |
| 17 | + * |
| 18 | + * It is guaranteed that every call to ping uses a strictly larger value of t than the previous call. |
| 19 | + * |
| 20 | + * Example 1: |
| 21 | + * Input |
| 22 | + * ["RecentCounter", "ping", "ping", "ping", "ping"] |
| 23 | + * [[], [1], [100], [3001], [3002]] |
| 24 | + * |
| 25 | + * Output |
| 26 | + * [null, 1, 2, 3, 3] |
| 27 | + * |
| 28 | + * Explanation: |
| 29 | + * RecentCounter recentCounter = new RecentCounter(); |
| 30 | + * recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 |
| 31 | + * recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 |
| 32 | + * recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 |
| 33 | + * recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 |
| 34 | + * </pre> |
| 35 | + */ |
| 36 | +public class NumberOfRecentCalls { |
| 37 | + |
| 38 | + private final Deque<Integer> deque; |
| 39 | + |
| 40 | + public NumberOfRecentCalls() { |
| 41 | + deque = new ArrayDeque<>(); |
| 42 | + } |
| 43 | + |
| 44 | + public int ping(int t) { |
| 45 | + deque.addLast(t); |
| 46 | + while (t - deque.peekFirst() > 3000) { |
| 47 | + deque.removeFirst(); |
| 48 | + } |
| 49 | + return deque.size(); |
| 50 | + } |
| 51 | +} |
0 commit comments