Using multiset, 3 line C++


  • 2
    U
    class HitCounter {
    public:
        /** Initialize your data structure here. */
        multiset<int>S;
        HitCounter() {
            
        }
        
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        void hit(int timestamp) {
            S.insert(timestamp);
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        int getHits(int timestamp) {
            int span = max(0, timestamp - 300);
            auto it = S.upper_bound(span), it2 = S.upper_bound(timestamp);
            return distance(it, it2);
        }
    };
    
    /**
     * Your HitCounter object will be instantiated and called as such:
     * HitCounter obj = new HitCounter();
     * obj.hit(timestamp);
     * int param_2 = obj.getHits(timestamp);
     */

  • 1
    Q

    Your multi_set will overflow pretty quickly.


Log in to reply
 

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