Web Logger

本文介绍如何实现一个Web日志记录器,它包含两个方法:记录指定时间戳的点击,并获取过去5分钟内的点击次数。方法调用按时间戳升序进行,可以使用Deque数据结构有效地处理这些操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement a web logger, which provide two methods:

  1. hit(timestamp), record a hit at given timestamp.
  2. get_hit_count_in_last_5_minutes(timestamp), get hit count in last 5 minutes.

the two methods will be called with non-descending timestamp (in sec).

Example

Example 1:

Input:
  hit(1);
  hit(2);
  get_hit_count_in_last_5_minutes(3);
  hit(300);
  get_hit_count_in_last_5_minutes(300);
  get_hit_count_in_last_5_minutes(301);
Output:
  2
  3
  2

Example 2:

Input:
  hit(1)
  hit(1)
  hit(1)
  hit(2)
  get_hit_count_in_last_5_minutes(3)
  hit(300)
  get_hit_count_in_last_5_minutes(300)
  get_hit_count_in_last_5_minutes(301)
  get_hit_count_in_last_5_minutes(302)
  get_hit_count_in_last_5_minutes(900)
  get_hit_count_in_last_5_minutes(900)
Output:
  4
  5
  2
  1
  0
  0

Notice

The unit of timestamp is seconds.

The call to the function is in chronological order, that is to say, timestamp is in ascending order.

思路:前面要弹出去,后面要加进来,用deque就可以解决;注意deque = new ArrayDeque<Integer>(); peekFirst(), pollFirst();

这题其实用queue做也可以,queue的poll, peek,offer 也可以做;

public class WebLogger {
    private Deque<Integer> deque;
    public WebLogger() {
        deque = new ArrayDeque<Integer>();
    }

    /*
     * @param timestamp: An integer
     * @return: nothing
     */
    public void hit(int timestamp) {
        // 这里也可以维护一个300size的queue;
        while(!deque.isEmpty() && timestamp - deque.peekFirst() >= 300) {
            deque.pollFirst();
        }
        deque.offer(timestamp);
    }

    /*
     * @param timestamp: An integer
     * @return: An integer
     */
    public int get_hit_count_in_last_5_minutes(int timestamp) {
        // 注意get_hit_count的时候,并没有往queue里面加东西;
        while(!deque.isEmpty() && timestamp - deque.peekFirst() >= 300) {
            deque.pollFirst();
        }
        return deque.size();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值