933. Number of Recent Calls

本文介绍了一个名为RecentCounter的类的设计,该类用于记录并返回过去3000毫秒内的ping请求数量。通过使用队列和 TreeMap 实现了两种解决方案,详细解释了每种方法的时间和空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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.

Example 1:

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

Note:

Each test case will have at most 10000 calls to ping.
Each test case will call ping with strictly increasing values of t.
Each call to ping will have 1 <= t <= 10^9.

Problem URL


Solution

设计一个RecencCouter类,输入一个带时间戳的ping(),返回最近3000ms内ping的数量。

Using a queue to implement this class. While peek value < t - 3000, poll it out.

Code
class RecentCounter {
    private Queue<Integer> queue;
    public RecentCounter() {
        queue = new LinkedList<Integer>();
    }
    
    public int ping(int t) {
        queue.offer(t);
        while (queue.peek() < t - 3000){
            queue.poll();
        }
        return queue.size();
    }
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */

Time Complexity: O(N)
Space Complexity: O(Math.min(N, 3000))


Review

Another approach using tree map. TailMap() method will return a map with key bigger than this key.

class RecentCounter {
    private TreeMap<Integer, Integer> map;
    public RecentCounter() {
        map = new TreeMap<Integer, Integer>();
    }
    
    public int ping(int t) {
        map.put(t, 1 + map.size());
        return map.tailMap(t - 3000).size();
    }
}

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */

`Time Complexity: O(log N)
Space Complexity: O(N)

C:\Users\23228\PyCharmMiscProject\.venv\Scripts\python.exe D:\commodity_sorting_system\code\main.py DATA_DIR: D:/commodity_sorting_system/data TRAIN_IMAGES: D:/commodity_sorting_system/data\train\images TRAIN_LABELS: D:/commodity_sorting_system/data\train\labels VAL_IMAGES: D:/commodity_sorting_system/data\val\images VAL_LABELS: D:/commodity_sorting_system/data\val\labels Error importing huggingface_hub.hf_api: cannot import name 'MutableMapping' from 'collections' (C:\Users\23228\AppData\Local\Programs\Python\Python312\Lib\collections\__init__.py) C:\Users\23228\PyCharmMiscProject\.venv\Lib\site-packages\albumentations\__init__.py:28: UserWarning: A new version of Albumentations is available: '2.0.8' (you have '2.0.7'). Upgrade using: pip install -U albumentations. To disable automatic update checks, set the environment variable NO_ALBUMENTATIONS_UPDATE to 1. check_for_updates() Number of images in D:/commodity_sorting_system/data\train\images: 11828 Number of samples in dataset: 11828 Number of images in D:/commodity_sorting_system/data\val\images: 500 Number of samples in dataset: 500 Epoch [1/100], Batch [1/740], Loss: 0.1528 Traceback (most recent call last): File "D:\commodity_sorting_system\code\main.py", line 35, in <module> loss.backward() File "C:\Users\23228\PyCharmMiscProject\.venv\Lib\site-packages\torch\_tensor.py", line 626, in backward torch.autograd.backward( File "C:\Users\23228\PyCharmMiscProject\.venv\Lib\site-packages\torch\autograd\__init__.py", line 347, in backward _engine_run_backward( File "C:\Users\23228\PyCharmMiscProject\.venv\Lib\site-packages\torch\autograd\graph.py", line 823, in _engine_run_backward return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ KeyboardInterrupt 进程已结束,退出代码为 1 为什么怎么解决
06-05
model [CycleGANModel] was created ---------- Networks initialized ------------- [Network G_A] Total number of parameters : 11.378 M [Network G_B] Total number of parameters : 11.378 M [Network D_A] Total number of parameters : 2.765 M [Network D_B] Total number of parameters : 2.765 M ----------------------------------------------- Setting up a new session... create web directory ./checkpoints\horse2zebra_cyclegan\web... D:\N 1\anaconda\Lib\site-packages\torch\optim\lr_scheduler.py:227: UserWarning: Detected call of `lr_scheduler.step()` before `optimizer.step()`. In PyTorch 1.1.0 and later, you should call them in the opposite order: `optimizer.step()` before `lr_scheduler.step()`. Failure to do this will result in PyTorch skipping the first value of the learning rate schedule. See more details at https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate warnings.warn( learning rate 0.0002000 -> 0.0002000 Traceback (most recent call last): File "E:\pytorch-CycleGAN-and-pix2pix-master\pytorch-CycleGAN-and-pix2pix-master\train.py", line 52, in <module> model.optimize_parameters() # calculate loss functions, get gradients, update network weights ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\pytorch-CycleGAN-and-pix2pix-master\pytorch-CycleGAN-and-pix2pix-master\models\cycle_gan_model.py", line 187, in optimize_parameters self.backward_G() # calculate gradients for G_A and G_B ^^^^^^^^^^^^^^^^^ File "E:\pytorch-CycleGAN-and-pix2pix-master\pytorch-CycleGAN-and-pix2pix-master\models\cycle_gan_model.py", line 178, in backward_G self.loss_G.backward() File "D:\N 1\anaconda\Lib\site-packages\torch\_tensor.py", line 626, in backward torch.autograd.backward( File "D:\N 1\anaconda\Lib\site-packages\torch\autograd\__init__.py", line 347, in backward _engine_run_backward( File "D:\N 1\anaconda\Lib\site-packages\torch\autograd\graph.py", line 823, in _engine_run_backward return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR_HOST_ALLOCATION_FAILED
05-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值