首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode 362. 敲击计数器(map)

LeetCode 362. 敲击计数器(map)

作者头像
Michael阿明
发布2020-07-13 16:30:18
发布2020-07-13 16:30:18
8680
举报

1. 题目

设计一个敲击计数器,使它可以统计在过去5分钟内被敲击次数。

每个函数会接收一个时间戳参数(以秒为单位),你可以假设最早的时间戳从1开始,且都是按照时间顺序对系统进行调用(即时间戳是单调递增)。

在同一时刻有可能会有多次敲击。

代码语言:javascript
复制
示例:
HitCounter counter = new HitCounter();

// 在时刻 1 敲击一次。
counter.hit(1);

// 在时刻 2 敲击一次。
counter.hit(2);

// 在时刻 3 敲击一次。
counter.hit(3);

// 在时刻 4 统计过去 5 分钟内的敲击次数, 函数返回 3 。
counter.getHits(4);

// 在时刻 300 敲击一次。
counter.hit(300);

// 在时刻 300 统计过去 5 分钟内的敲击次数,函数返回 4 。
counter.getHits(300);

// 在时刻 301 统计过去 5 分钟内的敲击次数,函数返回 3 。
counter.getHits(301); 

进阶:
如果每秒的敲击次数是一个很大的数字,你的计数器可以应对吗?

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/design-hit-counter 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
复制
class HitCounter {
    int kick = 0;
    map<int,int> m;
public:
    /** Initialize your data structure here. */
    HitCounter() {

    }
    
    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    void hit(int timestamp) {
        kick++;
        m[timestamp]++;
    }
    
    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    int getHits(int timestamp) {
        auto it = m.begin();
        while(it != m.end() && timestamp-it->first >= 300)//过期了
        {
            kick -= it->second;
            m.erase(it++);
        }
        return kick;
    }
};

0 ms 7.3 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档