Advertisement
nikunjsoni

362

Jun 24th, 2021
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. class HitCounter {
  2. private:
  3.     queue<pair<int, int> >  hits;
  4.     int cnt;
  5. public:
  6.     /** Initialize your data structure here. */
  7.     HitCounter() {
  8.         cnt = 0;
  9.     }
  10.    
  11.     /** Record a hit.
  12.         @param timestamp - The current timestamp (in seconds granularity). */
  13.     void hit(int timestamp) {
  14.         // maintain the queue to get rid of the outdated hit pair
  15.         while(!hits.empty() && timestamp - hits.front().first >= 300 ){
  16.             cnt -= hits.front().second;
  17.             hits.pop();
  18.         }
  19.         // count the current hit:
  20.         ++cnt;
  21.         if(!hits.empty() && timestamp == hits.back().first)  ++(hits.back().second);
  22.         else    hits.push(make_pair(timestamp,1));
  23.     }
  24.    
  25.     /** Return the number of hits in the past 5 minutes.
  26.         @param timestamp - The current timestamp (in seconds granularity). */
  27.     int getHits(int timestamp) {
  28.         while(!hits.empty() && timestamp - hits.front().first >= 300){
  29.             cnt -= hits.front().second;
  30.             hits.pop();
  31.         }
  32.         return cnt;
  33.     }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement