c++ vector implementation


  • 0
    T
    class HitCounter {
        vector<pair<long, long>> logger; // last hit time/hit count
    public:
        /** Initialize your data structure here. */
        HitCounter() {
            logger.reserve(300);
            for (int i = 0; i < 300; ++i)
                logger.emplace_back(0, 0);
        }
        
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        void hit(int timestamp) {
            int indx = --timestamp%300;
            if (logger[indx].first < timestamp) {
                logger[indx].first = timestamp, logger[indx].second = 1;
            }
            else ++logger[indx].second;
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        int getHits(int timestamp) {
            int cnt = 0;
            for (int i = 0, k = --timestamp; i < 300; ++i) {
                cnt += (k - logger[i].first < 300 ? logger[i].second:0);
            }
            return cnt;
        }
    };
    
    /**
     * Your HitCounter object will be instantiated and called as such:
     * HitCounter obj = new HitCounter();
     * obj.hit(timestamp);
     * int param_2 = obj.getHits(timestamp);
     */
    

Log in to reply
 

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