最近的请求次数
题目地址:933. 最近的请求次数 – 力扣(LeetCode) (leetcode-cn.com)
写在前面:
栈是一种后进先出的数据结构,元素从顶端入栈,然后从顶端出栈。
队列是一种先进先出的数据结构,元素从后端入队,然后从前端出队。
思路:
- 用队列存储这些ping记录
- 当收到t的ping,加入队列,同时将t-3000之前的ping移除队列
- 最后返回list的大小
class RecentCounter {
LinkedList<Integer> list;
public RecentCounter() {
list=new LinkedList<Integer>();
}
public int ping(int t) {
list.add(t);
while(list.get(0)<t-3000){
list.remove(0);
}
return list.size();
}
}
复杂度分析:
-
时间复杂度:O(X) ,X是ping的次数
-
空间复杂度:O(W) W=3000是队列中最多存储的ping的记录数目
用队列实现栈
题目地址:225. 用队列实现栈 – 力扣(LeetCode) (leetcode-cn.com)
思路:
- 一个队列即可
- push方法中,先获取到队列的大小
- 把传入的x值,入队列,
- for循环 每次将队列poll出来的值再入队列
举例 要添加2,7两个元素
- 首先push 2 进栈 就等同于 队列进 2
- 再push 7 进栈 ,此时 队列里就一个元素 2 ,队列中 先poll出2,让7入列,再将2入列 保证后进的元素先出
- pop 方法就是队列的poll方法
- top 方法 就是 队列的 peek方法
- empty 判断队列是否为空
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue=new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
int n=queue.size();
queue.offer(x);
for(int i=0;i<n;i++){
queue.offer(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
复杂度分析
- 时间复杂度:入栈操作 O(n),其余操作都是 O(1)。
- 空间复杂度:O(n),其中 n是栈内的元素。需要使用一个队列存储栈内的元素。
代码均由力扣编译器,提交通过,描述编写不当地方还请大家评论区指出💪!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/140728.html