文章目录
Question
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-recent-calls/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Ideas
1、Answer( Java ) - 队列实现
解法思路:队列实现
👍注意题目要求 :保证每次对 ping 调用所使用的 t 值都 严格递增( 相当于简化了问题 )
Code
/**
* @author Listen 1024
* @description 933. 最近的请求次数( 队列 或 数组模拟队列 )
* @date 2022-05-06 0:07
*/
class RecentCounter {
Queue<Integer> queue;
public RecentCounter() {
queue = new ArrayDeque<>();
}
public int ping(int t) {
queue.offer(t);
while (queue.peek() < t - 3000) {
queue.poll();
}
return queue.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
2、Answer( Java ) - 数组模拟队列
解法思路:数组模拟队列
⚡️OJ 常见奇技淫巧: CPU Cache 数是 2 的幂,N + 5 是一个奇数,与之互素,这样可以减少 Cache 冲突概率,提高速度。( 针对于多维数组 )
👍注意题目要求 :保证每次对 ping 调用所使用的 t 值都 严格递增( 相当于简化了问题 )
Code
/**
* @author Listen 1024
* @description 933. 最近的请求次数( 队列 或 数组模拟队列 )
* @date 2022-05-06 0:07
*/
class RecentCounter {
int left, right;
int[] res = new int[10005];
public RecentCounter() {
left = 0;
right = 0;
}
public int ping(int t) {
res[right++] = t;
while (res[left] < t - 3000) {
left++;
}
return right - left;
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
3、Answer( Java ) - 简单模拟
解法思路:简单模拟
👍暴力求解时间过长( 不推荐 )
Code
/**
* @author Listen 1024
* @description 933. 最近的请求次数( 队列 或 数组模拟队列 )
* @date 2022-05-06 0:07
*/
class RecentCounter {
List<Integer> list = new ArrayList<>();
public RecentCounter() {
}
public int ping(int t) {
int res = 0;
list.add(t);
for (Integer integer : list) {
if (integer >= t - 3000 && integer <= t) {
res++;
}
}
return res;
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
//部分题解参考链接(如侵删)
https://leetcode-cn.com/problems/number-of-recent-calls/solution/zui-jin-de-qing-qiu-ci-shu-by-leetcode-s-ncm1/
该博客详细介绍了如何使用Java解决LeetCode中的933题——最近的请求次数。作者提供了三种解决方案:使用队列、数组模拟队列以及简单模拟。其中,队列和数组模拟队列的解法更优,能够满足题目要求的严格递增条件,且在效率上优于暴力求解的简单模拟方法。

803

被折叠的 条评论
为什么被折叠?



