Leetcode 362 Solution

This article provides solution to leetcode question 362 (design-hit-counter)

https://leetcode.com/problems/design-hit-counter

Solution

class HitCounter {
    map<int, int> counts;
    int total;

public:
    /** Initialize your data structure here. */
    HitCounter() {
        total = 0;
    }

    void expire(int timestamp)
    {
        while (counts.empty() == false && timestamp >= counts.begin()->first + 300)
        {
            total -= counts.begin()->second;
            counts.erase(counts.begin());
        }
    }

    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    void hit(int timestamp) {
        total++;
        counts[timestamp]++;

        expire(timestamp);
    }

    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    int getHits(int timestamp) {
        expire(timestamp);
        return total;
    }
};

/**
 * Your HitCounter object will be instantiated and called as such:
 * HitCounter obj = new HitCounter();
 * obj.hit(timestamp);
 * int param_2 = obj.getHits(timestamp);
 */