Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 63e60c6

Browse files
add LeetCode 933. 最近的请求次数
1 parent 84f041e commit 63e60c6

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
2+
3+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
4+
>仰望星空的人,不应该被嘲笑
5+
6+
## 题目描述
7+
8+
9+
写一个` RecentCounter` 类来计算最近的请求。
10+
11+
它只有一个方法:`ping(int t)`,其中 t 代表以毫秒为单位的某个时间。
12+
13+
返回从 `3000 `毫秒前到现在的 ping 数。
14+
15+
任何处于` [t - 3000, t] `时间范围之内的 `ping` 都将会被计算在内,包括当前(指 t 时刻)的 `ping`
16+
17+
保证每次对 `ping` 的调用都使用比之前更大的 t 值。
18+
19+
20+
21+
示例:
22+
23+
```javascript
24+
输入:inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
25+
输出:[null,1,2,3,3]
26+
```
27+
28+
29+
30+
提示:
31+
32+
每个测试用例最多调用` 10000 `次 ping。
33+
每个测试用例会使用严格递增的 `t `值来调用 `ping`
34+
每次调用 ping 都有` 1 <= t <= 10^9`
35+
36+
37+
## 题解
38+
根据样例,发现越早发出的请求越早不在 `3000ms` 内的请求里
39+
40+
满足**先进先出**,考虑用队列
41+
42+
那么就将新请求加入队列,`3000ms`前发出的请求就出队列
43+
44+
45+
队列的长度即为最近请求次数。
46+
47+
```javascript
48+
var RecentCounter = function() {
49+
this.queue = []
50+
};
51+
52+
/**
53+
* @param {number} t
54+
* @return {number}
55+
*/
56+
RecentCounter.prototype.ping = function(t) {
57+
// 将新请求加入队列
58+
this.queue.push(t)
59+
// 3000ms 前发出的请求就出队列
60+
while(this.queue[0] < t-3000){
61+
this.queue.shift()
62+
}
63+
return this.queue.length
64+
};
65+
66+
/**
67+
* Your RecentCounter object will be instantiated and called as such:
68+
* var obj = new RecentCounter()
69+
* var param_1 = obj.ping(t)
70+
*/
71+
```
72+
73+
74+
75+
## 最后
76+
文章产出不易,还望各位小伙伴们支持一波!
77+
78+
往期精选:
79+
80+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
81+
82+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
83+
84+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
85+
86+
```javascript
87+
学如逆水行舟,不进则退
88+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /