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阿明),一起加油、一起學習進步!