Skip to content

Commit

Permalink
leetcode: Add 0933
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed May 8, 2024
1 parent 0dea95a commit 301f057
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/leetcode/0933.number-of-recent-calls/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0933-number-of-recent-calls"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
4 changes: 4 additions & 0 deletions src/leetcode/0933.number-of-recent-calls/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

#

[问题描述](../problems/)
62 changes: 62 additions & 0 deletions src/leetcode/0933.number-of-recent-calls/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. 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<i32>,
}

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();
}
}

0 comments on commit 301f057

Please sign in to comment.