最近的请求次数(java)

该博客介绍了如何使用Java实现一个记录最近3000次请求的计数器。提供了两种解决方案:一是结合LinkedList和HashSet进行查重和剪枝;二是利用ArrayDeque作为队列,不断移除过期请求。这两种方法都有效地处理了时间窗口内的请求计数问题。
摘要由CSDN通过智能技术生成

问题描述:
在这里插入图片描述
样例如下:
在这里插入图片描述
代码如下:两种思路

import java.util.*;
public class RecentCounter {
    //最近的请求次数
    //方法一
    List<Integer> list=new LinkedList<>();
    HashSet<Integer> hashSet=new HashSet<>();//利用hashset来加速查重
    int count=0;
    public RecentCounter() {//构造器
      this.count=0;
    }
    public int ping(int t) {
      this.list.add(t);
      hashSet.add(t);
      if (t-3000<=list.get(0)) return list.size();//剪枝
      if (list.size()>2)
      if (t-3000>list.get(list.size()-2)) return 1;
      if (!hashSet.contains(t-3000))//包含与不包含的情况是不相同的
      return this.list.size()-binarySearch(this.list,0,this.list.size()-1,t-3000)-1;
      else return this.list.size()-binarySearch(this.list,0,this.list.size()-1,t-3000);
    }
    //二分查找来查找t-300 的位置
    public int binarySearch(List<Integer> list,int st,int end,int t){//此处t表示为t-300的含义
        while (st<=end){
            int mid=(st+end)>>1;
            if (list.get(mid)<t) st=mid+1;
            else if (list.get(mid)>t) end=mid-1;
            else return mid;
        }
        return end;
    }
    //方法二  使用队列的方法进行
    //首先 将元素加入到队列中 ,然后从头部不断地弹出小于t-3000的元素即可,最后输出队列的长度
    class RecentCounter1 {
        Queue<Integer> queue;

        public RecentCounter1() {
            queue = new ArrayDeque<Integer>();
        }

        public int ping(int t) {
            queue.offer(t);
            while (queue.peek() < t - 3000) {
                queue.poll();
            }
            return queue.size();
        }
    }
    public static void main(String[] args) {
        RecentCounter recentCounter=new RecentCounter();
        Scanner scanner=new Scanner(System.in);
        while (true){
            System.out.println("请输入t");
            int t=scanner.nextInt();
            System.out.println("结果为   "+recentCounter.ping(t));
            System.out.println("list中的内容为   "+recentCounter.list.toString());
        }
    }

}

运行结果如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lianggege88

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值