LeetCode 362. 敲击计数器(map)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 362. 敲击计数器(map)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
設計一個敲擊計數器,使它可以統計在過去5分鐘內被敲擊次數。
每個函數會接收一個時間戳參數(以秒為單位),你可以假設最早的時間戳從1開始,且都是按照時間順序對系統進行調用(即時間戳是單調遞增)。
在同一時刻有可能會有多次敲擊。
示例: 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. 解題
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
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 362. 敲击计数器(map)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 949. 给定数字能组
- 下一篇: LeetCode 276. 栅栏涂色(D