刷题笔记(队列)-05

最近的请求次数

题目地址: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)

image-20210518135835839

思路:

  • 一个队列即可
  • 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是栈内的元素。需要使用一个队列存储栈内的元素。

代码均由力扣编译器,提交通过,描述编写不当地方还请大家评论区指出💪!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值