Skip to content

Instantly share code, notes, and snippets.

@NodoFox
Last active October 25, 2018 00:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NodoFox/7e3ee62f53cc29d11aa74d811ba86393 to your computer and use it in GitHub Desktop.
Save NodoFox/7e3ee62f53cc29d11aa74d811ba86393 to your computer and use it in GitHub Desktop.
[LeetCode] Design Hit Counter
// Counts the number of hits in the past 5 minutes.
//Each function accepts a timestamp parameter (in seconds granularity) and
//you may assume that calls are being made to the system in chronological order
//(ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
//It is possible that several hits arrive roughly at the same time.
public class HitCounter {
int windowSize = 5 * 60; // since time interval is in seconds.
Map<Long, Long> timeStampBucket = new HashMap<Long, Long>();
long minStamp = 0;
long totalHits = 0;
public void logHits(long timeStamp) {
cleanUp(timeStamp);
if(timeStampBucket.containsKey(timeStamp)) {
timeStampBucket.put(timeStamp, 1);
}else {
timeStampBucket.put(timeStamp, timeStampBucket.get(timeStamp) + 1);
}
totalHits++;
}
public long getHits(long timeStamp) {
cleanUp(timeStamp); // usually stays current timeStamp
return totalHits;
}
private void cleanUp(long timeStamp) {
while(timeStamp - minStamp > windowSize) {
if(timeStampBucket.containsKey(minStamp)) {
totalHits -= timeStampBucket.get(minStamp);
timeStampBucket.remove(minStamp++);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment