2021-12-7 力扣(队列)

1. 933最近的请求次数

在这里插入图片描述
answer:
stack: push pop;
queue: add,poll;

    Queue<Integer> q;
    public RecentCounter() {
        q = new ArrayDeque<>();
    }
    
    public int ping(int t) {
        q.add(t);
        while (q.peek() < t-3000) {
            q.poll();
        }
        return q.size();
    }

2. 225用队列实现栈(还要再刷)

在这里插入图片描述

answer:
第一次做!有点意思;
类似的:用栈实现队列;

Queue<Integer> q;
    int top = 0;
    public MyStack() {
        q = new ArrayDeque<>();
    }
    
    public void push(int x) {
        q.add(x);
        top = x;
    }
    
    public int pop() {
        if (q.isEmpty())
            return -1;
        int s = q.size();
        while (s > 2) {
            q.add(q.poll());
            s--;
        }
        top = q.poll();
        q.add(top);
        return q.poll();
    }
    
    public int top() {
        return top;
    }
    
    public boolean empty() {
        if (q.isEmpty())
            return true;
        return false;
    }

3. 232用栈实现队列(还要再刷)

在这里插入图片描述
answer:
key:

private Stack<Integer> s1, s2;
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }
    
    public void push(int x) {
        s1.push(x);
    }
    
    public int pop() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.pop();
    }
    
    public int peek() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }
    
    public boolean empty() {
        return s1.isEmpty() && s2.isEmpty();
    }

参考:
队列实现栈|栈实现队列

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值