728x90
반응형
✨ 문제
Number of Recent Calls
You have a RecentCounter class which 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 has 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.
https://leetcode.com/problems/number-of-recent-calls/description/
✨ 최종코드
class RecentCounter {
private Queue<Integer> requests;
public RecentCounter() {
requests = new LinkedList<>();
}
public int ping(int t) {
// 현재 요청을 큐에 추가
requests.add(t);
// 유효하지 않은 요청 (3000ms 이전)을 큐에서 제거
while (requests.peek() < t - 3000) {
requests.poll();
}
// 현재 시점 t부터 3000ms 이내의 요청 수 반환
return requests.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
728x90
반응형