Leetcode 933 Number of Recent Calls

HowieLee59發表於2018-11-04

Write a class RecentCounter to count recent requests.

It has only one method: ping(int t), where t represents some time in milliseconds.

Return the number of pings that have been made from 3000 milliseconds ago until now.

Any ping with time in [t - 3000, t] will count, including the current ping.

It is guaranteed that every call to ping uses a strictly larger value of t than before.

 

Example 1:

Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]

這個題的意思是找到在給定數字中符合條件的部分。

1)

class RecentCounter {
    PriorityQueue<Integer> queue = new PriorityQueue<>();
    public RecentCounter() {
        
    }
    
    public int ping(int t) {
        queue.add(t);
        while(queue.peek() < t - 3000){
            queue.poll();
        }
        return queue.size();
    }
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */

2)

class RecentCounter {
    set<int> history;
public:
    int ping(int t) {
        history.insert( t );
        return distance( history.lower_bound( t - 3000 ), history.end() );
    }
};

 

相關文章