【队列】【实现构造函数和方法】Leetcode 903 最近的请求次数

【队列相关】【实现构造函数和方法】Leetcode 903 最近的请求次数

---------------🎈🎈题目链接🎈🎈-------------------

在这里插入图片描述

解法1 利用列表的相关操作

1、新建类型为Queue<Integer>,表示这是一个能够存储整数类型的队列
2、构造器函数用于初始化myqueue队列
3、调用ping方法,当前t减去队列顶部值,大于3000就弹出顶部值,满足小于3000后当前值入队,得到队列长度返回值

⭐️列表相关的方法:
新建队列:Queue<Integer> myqueue = new LinkedList<>();
返回队列大小:myqueue.size()
返回队列:myqueue.peek()
队列头部弹出:myqueue.poll()
队列尾部插入:myqueue.add()

时间复杂度O(N)
空间复杂度O(N)

class RecentCounter {
   

    Queue<Integer> myqueue;
    
	// 构造器函数用于初始化myqueue队列
    public RecentCounter() {
   
        myqueue = new LinkedList<>();
    }
    
    // 调用ping方法,得到返回值
    public int ping(int t) {
    
        while(myqueue.size() > 0 && t-myqueue.peek() > 3000){
   
            myqueue.poll();
        }
        myqueue.add(t);
        return myqueue.size();
    }
}


/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();  实例化一个RecentCounter对象
 * int param_1 = obj.ping(t);
 */
         
    

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-29 18:14:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-29 18:14:03       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-29 18:14:03       87 阅读
  4. Python语言-面向对象

    2023-12-29 18:14:03       96 阅读

热门阅读

  1. 算法系统学习(持续更新)

    2023-12-29 18:14:03       57 阅读
  2. 深入理解Dockerfile —— 筑梦之路

    2023-12-29 18:14:03       55 阅读
  3. GPT翻译水平探究:人工智能的语言艺术

    2023-12-29 18:14:03       55 阅读
  4. 23种设计模式学习

    2023-12-29 18:14:03       54 阅读
  5. go语言面试一逃逸分析

    2023-12-29 18:14:03       57 阅读
  6. APP接入小游戏的崭新趋势

    2023-12-29 18:14:03       51 阅读
  7. 嵌入式软件测试

    2023-12-29 18:14:03       65 阅读
  8. redis缓存与数据库同步策略

    2023-12-29 18:14:03       52 阅读