clueless coding // TODO: be smarter

LeetCode Design Hit Counter: CPP Solution



TL;DR Code Solution



vector<int> timestamps;
vector<int> counters;

/** Initialize your data structure here. */
HitCounter() {
    timestamps.resize(300);
    counters.resize(300);
}

/** Record a hit.
    @param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
    int index = timestamp % 300;
    if (timestamps[index] != timestamp) {
        timestamps[index] = timestamp;
        counters[index] = 0;
    }
    counters[index]++;

}

/** Return the number of hits in the past 5 minutes.
    @param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
    int total = 0;
    for (int i = 0; i < counters.size(); i++) {
        if (timestamp - timestamps[i] < 300) {
            total += counters[i];
        }
    }
    return total;
}