From 4b36bc29ed088e4a0a1c5151cd52dd31c6012485 Mon Sep 17 00:00:00 2001 From: openset Date: Sat, 23 Feb 2019 12:35:12 +0800 Subject: [PATCH] Add: Number of Recent Calls --- .../number_of_recent_calls.go | 24 ++++++++++++++++ .../number_of_recent_calls_test.go | 28 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/problems/number-of-recent-calls/number_of_recent_calls.go b/problems/number-of-recent-calls/number_of_recent_calls.go index 25e3da579..d12b82063 100644 --- a/problems/number-of-recent-calls/number_of_recent_calls.go +++ b/problems/number-of-recent-calls/number_of_recent_calls.go @@ -1 +1,25 @@ package number_of_recent_calls + +import "container/list" + +type RecentCounter struct { + queue *list.List +} + +func Constructor() RecentCounter { + return RecentCounter{list.New()} +} + +func (this *RecentCounter) Ping(t int) int { + this.queue.PushBack(t) + for this.queue.Front().Value.(int) < t-3000 { + this.queue.Remove(this.queue.Front()) + } + return this.queue.Len() +} + +/** + * Your RecentCounter object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Ping(t); + */ diff --git a/problems/number-of-recent-calls/number_of_recent_calls_test.go b/problems/number-of-recent-calls/number_of_recent_calls_test.go index 25e3da579..73f575b73 100644 --- a/problems/number-of-recent-calls/number_of_recent_calls_test.go +++ b/problems/number-of-recent-calls/number_of_recent_calls_test.go @@ -1 +1,29 @@ package number_of_recent_calls + +import ( + "reflect" + "testing" +) + +type caseType struct { + input []int + expected []int +} + +func TestConstructor(t *testing.T) { + tests := [...]caseType{ + { + input: []int{1, 100, 3001, 3002}, + expected: []int{1, 2, 3, 3}, + }, + } + for _, tc := range tests { + obj, output := Constructor(), make([]int, 0) + for _, t := range tc.input { + output = append(output, obj.Ping(t)) + } + if !reflect.DeepEqual(output, tc.expected) { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}