剑指 Offer II 042. 最近请求次数(933. 最近的请求次数)

题目:

 

 

 

思路:

【1】利用队列的形式

【2】快慢指针的思路(但这个思路局限于对场景的限制,首先限制了ping调用最多一万次,所以固定了填充的数组大小,如果没有限制呢,大体又是队列的模式了,或者环状也可以)

//C++版本
class RecentCounter {
public:
    array<int,10005> vec;
    /* 定义快慢指针 */
    int slowIndex, fastIndex;
    /* 构造函数初始化 */
    RecentCounter() {
        slowIndex = 0;
        fastIndex = 0;
    }
    
    int ping(int t) {
        vec[fastIndex++] = t;
        while(vec[slowIndex] < t - 3000)
            slowIndex++;
        /* 返回数组的大小 = 发生的请求数 */
        return fastIndex - slowIndex;
    }
};

 

 

 

代码展示:

利用队列的形式:

//时间19 ms击败81.84%
//内存49.3 MB击败69.66%
//时间复杂度:均摊 O(1),每个元素至多入队出队各一次。
//空间复杂度:O(L),其中 L 为队列的最大元素个数。
class RecentCounter {
    private Deque<Integer> queue = new LinkedList<>();
    public RecentCounter() {

    }
    
    public int ping(int t) {
        while(!queue.isEmpty() && queue.peekFirst()<t-3000)
            queue.pollFirst();
        queue.offer(t);
        return queue.size();
    }
}

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

 

posted @ 2023-03-02 14:54  忧愁的chafry  阅读(24)  评论(0)    收藏  举报