队列的基本操作

import java.util.LinkedList;
import java.util.Queue;

public class test01 {
    public static void main(String[] args) {
        //创建队列  创建链表来增加删除这个队列
        Queue <Integer> queue = new LinkedList<>();
        //添加元素
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        System.out.println(queue.toString());
        //获取一个元素,使用peek,这个的意思即将出队的元素,先来先出队,也就是1

       /* int temp1 = queue.peek();
        System.out.println(temp1);*/

        //删除一个元素,使用poll,这个的意思删除即将出队的元素
        int temp2 = queue.poll();
        System.out.println(temp2);
        System.out.println(queue.toString());

        //判断队列的元素是否为空,使用isEmpty,如果是空的返回一个true,不是空的则返回一个false。
        System.out.println(queue.isEmpty());

        //判断队列的长度 O(1),它的时间复杂度是O(1)
        System.out.println(queue.size());

        //遍历队列
        while (!queue.isEmpty()){
            int temp = queue.poll();
            System.out.println("遍历的队列是"+":"+temp);
        }

    }
}

933. 最近的请求次数

难度简单212

写一个 RecentCounter 类来计算特定时间范围内最近的请求。

请你实现 RecentCounter 类:

  • RecentCounter() 初始化计数器,请求数为 0 。
  • int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。

保证 每次对 ping 的调用都使用比之前更大的 t 值。

思路 

首先初始化队列, RecentCounter为默认,当这个队列不为空或者队列的入队数字小于t减去3000那么就要出队,也就是说超出3000这个范围的数字就应该出队

class RecentCounter {
    Queue<Integer> queue = new LinkedList<>();
    public RecentCounter() {

    }

    public int ping(int t) {
        while(!queue.isEmpty() && queue.peek()<t-3000){
            queue.poll();
        }
        queue.add(t);
        return queue.size();
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值