# C#LeetCode刷题之#933-最近的请求次数（Number of Recent Calls）

• 每个测试用例最多调用 10000 次 ping。
• 每个测试用例会使用严格递增的 t 值来调用 ping。
• 每次调用 ping 都有 1 <= t <= 10^9。

Write a class RecentCounter to count recent requests.

It has only one method: ping(int t), where t represents some time in milliseconds.

Return the number of pings that have been made from 3000 milliseconds ago until now.

Any ping with time in [t – 3000, t] will count, including the current ping.

It is guaranteed that every call to ping uses a strictly larger value of t than before.

Input: inputs = [“RecentCounter”,”ping”,”ping”,”ping”,”ping”], inputs = [[],[1],[100],[3001],[3002]]

Output: [null,1,2,3,3]

Note:

• Each test case will have at most 10000 calls to ping.
• Each test case will call ping with strictly increasing values of t.
• Each call to ping will have 1 <= t <= 10^9.

```public class Program {

public static void Main(string[] args) {
var count = new RecentCounter();

Console.WriteLine(count.Ping(1));
Console.WriteLine(count.Ping(100));
Console.WriteLine(count.Ping(3001));
Console.WriteLine(count.Ping(3002));

Console.WriteLine();

var count2 = new RecentCounter2();

Console.WriteLine(count2.Ping(1));
Console.WriteLine(count2.Ping(100));
Console.WriteLine(count2.Ping(3000));
Console.WriteLine(count2.Ping(5000));

}

public class RecentCounter {

public RecentCounter() {
_list = new List<int>();
}

private List<int> _list = null;

public int Ping(int t) {
//列表法，思路简单暴力
var last = _list[_list.Count - 1];
var count = 1;
for(var i = _list.Count - 2; i >= 0; i--) {
if(last - _list[i] <= 3000) {
count++;
} else {
break;
}
}
return count;
}

}

public class RecentCounter2 {

public RecentCounter2() {
_queue = new Queue<int>();
}

private Queue<int> _queue = null;

public int Ping(int t) {
//队列法
_queue.Enqueue(t);
//干掉时间差大于 3000 的，它们没有必要参与运算
while(t - _queue.Peek() > 3000) _queue.Dequeue();
return _queue.Count;
}

}

}```

```1
2
3
3

1
2
3
2```

(6)