From 301f05743bf40590fec467360686f69d251902da Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Wed, 8 May 2024 17:43:04 +0800 Subject: [PATCH] leetcode: Add 0933 --- .../0933.number-of-recent-calls/Cargo.toml | 7 +++ .../0933.number-of-recent-calls/index.md | 4 ++ .../0933.number-of-recent-calls/src/main.rs | 62 +++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 src/leetcode/0933.number-of-recent-calls/Cargo.toml create mode 100644 src/leetcode/0933.number-of-recent-calls/index.md create mode 100644 src/leetcode/0933.number-of-recent-calls/src/main.rs diff --git a/src/leetcode/0933.number-of-recent-calls/Cargo.toml b/src/leetcode/0933.number-of-recent-calls/Cargo.toml new file mode 100644 index 00000000..87b2e25a --- /dev/null +++ b/src/leetcode/0933.number-of-recent-calls/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-0933-number-of-recent-calls" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/src/leetcode/0933.number-of-recent-calls/index.md b/src/leetcode/0933.number-of-recent-calls/index.md new file mode 100644 index 00000000..77a618ba --- /dev/null +++ b/src/leetcode/0933.number-of-recent-calls/index.md @@ -0,0 +1,4 @@ + +# + +[问题描述](../problems/) diff --git a/src/leetcode/0933.number-of-recent-calls/src/main.rs b/src/leetcode/0933.number-of-recent-calls/src/main.rs new file mode 100644 index 00000000..076d2cac --- /dev/null +++ b/src/leetcode/0933.number-of-recent-calls/src/main.rs @@ -0,0 +1,62 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +use std::collections::VecDeque; + +#[derive(Debug, Clone)] +pub struct RecentCounter { + queue: VecDeque, +} + +impl Default for RecentCounter { + fn default() -> Self { + Self::new() + } +} + +impl RecentCounter { + #[must_use] + #[inline] + pub fn new() -> Self { + Self { + queue: VecDeque::new(), + } + } + + #[must_use] + pub fn ping(&mut self, t: i32) -> i32 { + const SPAN: i32 = 3000; + self.queue.push_back(t); + while let Some(front) = self.queue.front() { + if front + SPAN < t { + self.queue.pop_front(); + } else { + break; + } + } + self.queue.len() as i32 + } +} + +fn check_solution() { + let mut obj = RecentCounter::new(); + assert_eq!(obj.ping(1), 1); + assert_eq!(obj.ping(100), 2); + assert_eq!(obj.ping(3001), 3); + assert_eq!(obj.ping(3002), 3); +} + +fn main() { + check_solution(); +} + +#[cfg(test)] +mod tests { + use super::check_solution; + + #[test] + fn test_counter() { + check_solution(); + } +}