LeetCode:933. Number of Recent Calls

題目:

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.

範例:

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

解法:
這題是只保留最近三秒的請求
ping指令可以用來測試對某個網路設備有沒有通(可以參考

但題目有說
要先定義一個struct以及其方法
我是覺得用queue是最好的方式了
但Golang沒有standard queue庫
所以直接就用迴圈硬做了
導至效能很差

type RecentCounter struct {    count int    pingRecord []int}func Constructor() RecentCounter {    return RecentCounter{        count: 0,        pingRecord:  []int{},    }}func (this *RecentCounter) Ping(t int) int {	this.count++	this.pingRecord = append(this.pingRecord, t)	for index, value := range this.pingRecord {		if value != 0 &&  t-value > 3000{			this.count--			this.pingRecord[index] = 0		}	}	return this.count}/** * Your RecentCounter object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Ping(t); */

沒有留言:

張貼留言

About

努力在程式的大海
用力的揮動雙手
找出屬於自己的航線

Blog Archive

Traffic