Design and implement a HitCounter class that keeps track of requests (or hits). It should support the following operations:
record(timestamp)
: records a hit that happened attimestamp
total()
: returns the total number of hits recordedrange(lower, upper)
: returns the number of hits that occurred between timestampslower
andupper
(inclusive)
Example:
Input: counter.hit(1);Output: [3,4,3]// hit at timestamp 2. counter.hit(2); // hit at timestamp 3. counter.hit(3); // get hits at timestamp 4, should return 3. counter.getHits(4); // hit at timestamp 300. counter.hit(300); // get hits at timestamp 300, should return 4. counter.getHits(300); // get hits at timestamp 301, should return 3. counter.getHits(301);
Approach
C++
#include <bits/stdc++.h>using namespace std;class HitCounter{public:HitCounter(){times.resize(300);hits.resize(300);}void hit(int timestamp){int idx = timestamp % 300;if (times[idx] != timestamp){times[idx] = timestamp;hits[idx] = 1;}else{++hits[idx];}}int getHits(int timestamp){int res = 0;for (int i = 0; i < 300; ++i){if (timestamp - times[i] < 300){res += hits[i];}}return res;}private:vector<int> times, hits;};int main(){HitCounter counter;counter.hit(1);counter.hit(2);counter.hit(3);cout << "[";cout << counter.getHits(4) << ", ";counter.hit(300);cout << counter.getHits(300) << ", ";cout << counter.getHits(301);cout << "]";return 0;}
No comments:
Post a Comment