- 题目描述
- 思路
- 集合或列表+模拟
- Python实现
- Java实现
- 队列模拟
- Python实现
- Java实现
题目描述
最近的请求次数
思路 集合或列表+模拟
java使用集合实现,python使用列表实现。根据题意,每次调用ping时都使用比之前更大的时间值,所以这是一个有序集合或有序列表。所以可以对集合或列表逐个位置判断是否满足条件,不满足的删除,直到第一个满足条件的值出现或集合列表为空为止,加入本次操作的时间,并返回当前集合或列表长度。
Python实现class RecentCounter:
def __init__(self):
self.opt = []
def ping(self, t: int) -> int:
while len(self.opt) > 0 and self.opt[0] < t-3000:
self.opt.pop(0)
self.opt.append(t)
return len(self.opt)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)
Java实现
class RecentCounter {
private List lst;
public RecentCounter() {
lst = new ArrayList();
}
public int ping(int t) {
while (lst.size() > 0 && lst.get(0) < t-3000) {
lst.remove(0);
}
lst.add(t);
return lst.size();
}
}
队列模拟
与集合、列表思路类似。
Python实现class RecentCounter:
def __init__(self):
self.q = deque()
def ping(self, t: int) -> int:
while self.q and self.q[0] < t-3000:
self.q.popleft()
self.q.append(t)
return len(self.q)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)
Java实现
class RecentCounter {
private Deque q;
public RecentCounter() {
q = new ArrayDeque();
}
public int ping(int t) {
while (!q.isEmpty() && q.peekFirst() < t-3000) {
q.pollFirst();
}
q.addLast(t);
return q.size();
}
}



