列表

详情


933. 最近的请求次数

写一个 RecentCounter 类来计算特定时间范围内最近的请求。

请你实现 RecentCounter 类:

保证 每次对 ping 的调用都使用比之前更大的 t 值。

 

示例 1:

输入:
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
输出:
[null, 1, 2, 3, 3]

解释:
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1);     // requests = [1],范围是 [-2999,1],返回 1
recentCounter.ping(100);   // requests = [1, 100],范围是 [-2900,100],返回 2
recentCounter.ping(3001);  // requests = [1, 100, 3001],范围是 [1,3001],返回 3
recentCounter.ping(3002);  // requests = [1, 100, 3001, 3002],范围是 [2,3002],返回 3

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class RecentCounter { public: RecentCounter() { } int ping(int t) { } }; /** * Your RecentCounter object will be instantiated and called as such: * RecentCounter* obj = new RecentCounter(); * int param_1 = obj->ping(t); */

golang 解法, 执行用时: 136 ms, 内存消耗: 8.4 MB, 提交时间: 2021-06-10 16:42:42

type RecentCounter struct {
    req []int
}


func Constructor() RecentCounter {
    return RecentCounter{
        req: []int{},
    }
}


func (this *RecentCounter) Ping(t int) int {
    this.req = append(this.req, t)
    for this.req[0] < t - 3000 {
        this.req = this.req[1:]
    }
    
    return len(this.req)
}


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

golang 解法, 执行用时: 268 ms, 内存消耗: 8.5 MB, 提交时间: 2021-06-10 16:37:55

type RecentCounter struct {
    req []int
    counter int
}


func Constructor() RecentCounter {
    return RecentCounter{
        req: []int{},
        counter: 0,
    }
}


func (this *RecentCounter) Ping(t int) int {
    this.req = append(this.req, t)
    begin, end := t-3000, t
    this.counter++
    ans := 0
    for _, n := range this.req {
        if n >= begin && n <= end {
            ans++
        }
    }

    return ans 
}


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

上一题