C++ solution


  • 0
    T

    The idea is to save the number of total hit in m_TotalHit member variable. m_Map is the map whose key is the timestamp and whose value is the number of hit until the timestamp that stored as the key.

    class HitCounter {
    public:
        /** Initialize your data structure here. */
        HitCounter() {
            m_TotalHit = 0;
        }
        
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        void hit(int timestamp) {
            if(m_Map.size()==0 || m_Map.find(timestamp)!=m_Map.end())
            {
                m_Map[timestamp]++;
                
            }
            else
            {
                map<int, int>::iterator iter= m_Map.end();
                iter--;
                m_Map[timestamp]=iter->second+1;            
            }
            m_TotalHit++;
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        int getHits(int timestamp) {
            if(timestamp<=300)
                return m_TotalHit;
            int gap=timestamp-300;
            map<int, int>::iterator iter=m_Map.upper_bound(gap);
            if(iter==m_Map.begin())
                return m_TotalHit;
            else{
                iter--;
                return m_TotalHit-iter->second;
            }
        }
    private: 
        map<int, int> m_Map;
        int m_TotalHit;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.