O(logN) for getHits and O(1) hits opearation ,Easy Binary Search


  • 0
    A
    class HitCounter {
    public:
        /** Initialize your data structure here. */
        vector<int>v;
       
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        void hit(int timestamp) {
            v.push_back(timestamp) ;
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        int getHits(int timestamp) {
            int a1 = v.size()  - 1;
            timestamp -= 300;
            if(timestamp<0)
                timestamp = 0 ;
            int a2 = upper_bound(v.begin() , v.end() , timestamp) - v.begin() ;
            return a1-a2+1; 
            
        }
    };
    
    /**
     * 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.