调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
中等
相关标签
相关企业
提示

A Rate Limiting System can allow a maximum of n requests every t seconds, using an implementation similar to the sliding window algorithm.

Given two positive integers n and t, and a non-decreasing stream of integers representing the timestamps of requests, implement a data structure that can check if each request is allowed or not.

Implement the RateLimiter class:

  • RateLimiter(int n, int t) Initializes the RateLimiter object with an empty stream and two integers n and t.
  • boolean shouldAllow(int timestamp) Returns true if the current request with timestamp timestamp is allowed, otherwise returns false. Note that while checking if the current request should be allowed, only the timestamps of requests previously allowed are considered.

 

Example 1:

Input
["RateLimiter", "shouldAllow", "shouldAllow", "shouldAllow", "shouldAllow", "shouldAllow"]
[[3, 5], [1], [1], [2], [3], [8]]
Output
[null, true, true, true, false, true]

Explanation
RateLimiter rateLimiter = new RateLimiter(3, 5);
rateLimiter.shouldAllow(1); // returns True
                            // There are no previous requests, so this request is allowed.
rateLimiter.shouldAllow(1); // returns True
                            // We can allow 3 requests every 5 seconds, so this request is allowed.
                            // Timestamps of allowed requests are [1,1].
rateLimiter.shouldAllow(2); // returns True
                            // Timestamps of allowed requests are [1,1,2].
rateLimiter.shouldAllow(3); // returns False
                            // This request is not allowed because
                            // the time range [1,3] already has 3 allowed requests.
rateLimiter.shouldAllow(8); // returns True
                            // This request is allowed because
                            // the time range [4,8] does not have any allowed requests.

 

Constraints:

  • 1 <= n <= 105
  • 1 <= t, timestamp <= 105
  • At most 105 calls will be made to shouldAllow.
  • timestamp values will be non-decreasing over all calls made to shouldAllow.
通过次数
16
提交次数
29
通过率
55.2%

相关标签

相关企业

提示 1
How can we store the number of accepted requests in a time range of size t?

提示 2
Since timestamps of requests will be given in non-decreasing order, which requests should we store for future reference?


评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
["RateLimiter","shouldAllow","shouldAllow","shouldAllow","shouldAllow","shouldAllow"]
[[3,5],[1],[1],[2],[3],[8]]
Source