46 lines
849 B
Go
46 lines
849 B
Go
package q933
|
|
|
|
type RecentCounter struct{ reqs []int }
|
|
|
|
func Constructor() RecentCounter {
|
|
return RecentCounter{reqs: make([]int, 0, 1024)}
|
|
}
|
|
|
|
func (c *RecentCounter) Ping(t int) int {
|
|
if cap(c.reqs) == len(c.reqs) {
|
|
alloc := make([]int, max(2048, 2*len(c.reqs)))
|
|
copy(alloc, c.reqs)
|
|
c.reqs = alloc[:len(c.reqs)]
|
|
}
|
|
|
|
c.reqs = append(c.reqs, t)
|
|
|
|
// Fast path
|
|
if len(c.reqs) < 8 || c.reqs[7] >= t-3000 {
|
|
i := 0
|
|
for c.reqs[i] < t-3000 {
|
|
i++
|
|
}
|
|
c.reqs = c.reqs[i:]
|
|
return len(c.reqs)
|
|
}
|
|
|
|
// Use binary search to find the cut position
|
|
l, r := 0, len(c.reqs)
|
|
for l < r {
|
|
m := (l + r) / 2
|
|
if c.reqs[m] < t-3000 {
|
|
l = m + 1
|
|
} else {
|
|
r = m
|
|
}
|
|
}
|
|
c.reqs = c.reqs[l:]
|
|
return len(c.reqs)
|
|
}
|
|
|
|
/**
|
|
* Your RecentCounter object will be instantiated and called as such:
|
|
* obj := Constructor();
|
|
* param_1 := obj.Ping(t);
|
|
*/
|