[LeetCode] 362. Design Hit Counter 设计点击计数器
Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
It is possible that several hits arrive roughly at the same time.
Example:
HitCounter counter = new HitCounter(); // hit at timestamp 1.
counter.hit(1); // hit at timestamp 2.
counter.hit(2); // hit at timestamp 3.
counter.hit(3); // get hits at timestamp 4, should return 3.
counter.getHits(4); // hit at timestamp 300.
counter.hit(300); // get hits at timestamp 300, should return 4.
counter.getHits(300); // get hits at timestamp 301, should return 3.
counter.getHits(301);
Follow up:
What if the number of hits per second could be very large? Does your design scale?
设计一个点击计数器,能够返回五分钟内的点击数,提示了有可能同一时间内有多次点击。
解法:要求保证时间顺序,可以用一个queue将每次点击的timestamp放入queue中。getHits: 可以从queue的头开始看, 如果queue开头的时间在范围外,就poll掉。最后返回queue的size。
Java:
public class HitCounter {
private ArrayDeque<Integer> queue;
/** Initialize your data structure here. */
public HitCounter() {
queue = new ArrayDeque<Integer>();
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
public void hit(int timestamp) {
queue.offer(timestamp);
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
public int getHits(int timestamp) {
int startTime = timestamp - 300;
while(!queue.isEmpty() && queue.peek() <= startTime) {
queue.poll();
}
return queue.size();
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
Java:
public class HitCounter {
private Hit start = new Hit(0);
private Hit tail = start;
private int count = 0;
/** Initialize your data structure here. */
public HitCounter() {
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
public void hit(int timestamp) {
if (tail.timestamp == timestamp) {
tail.count ++;
count ++;
} else {
tail.next = new Hit(timestamp);
tail = tail.next;
count ++;
}
getHits(timestamp);
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
public int getHits(int timestamp) {
while (start.next != null && timestamp - start.next.timestamp >= 300) {
count -= start.next.count;
start.next = start.next.next;
}
if (start.next == null) tail = start;
return count;
}
}
class Hit {
int timestamp;
int count;
Hit next;
Hit(int timestamp) {
this.timestamp = timestamp;
this.count = 1;
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
Python:
# Time: O(1), amortized
# Space: O(k), k is the count of seconds. from collections import deque class HitCounter(object): def __init__(self):
"""
Initialize your data structure here.
"""
self.__k = 300
self.__dq = deque()
self.__count = 0 def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: void
"""
self.getHits(timestamp)
if self.__dq and self.__dq[-1][0] == timestamp:
self.__dq[-1][1] += 1
else:
self.__dq.append([timestamp, 1])
self.__count += 1 def getHits(self, timestamp):
"""
Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: int
"""
while self.__dq and self.__dq[0][0] <= timestamp - self.__k:
self.__count -= self.__dq.popleft()[1]
return self.__count # Your HitCounter object will be instantiated and called as such:
# obj = HitCounter()
# obj.hit(timestamp)
# param_2 = obj.getHits(timestamp)
C++:
// Time: O(1), amortized
// Space: O(k), k is the count of seconds. class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() : count_(0) { } /** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
getHits(timestamp);
if (!dq_.empty() && dq_.back().first == timestamp) {
++dq_.back().second;
} else {
dq_.emplace_back(timestamp, 1);
}
++count_;
} /** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
while (!dq_.empty() && dq_.front().first <= timestamp - k_) {
count_ -= dq_.front().second;
dq_.pop_front();
}
return count_;
} private:
const int k_ = 300;
int count_;
deque<pair<int, int>> dq_;
}; /**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
C++:
class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() {}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
q.push(timestamp);
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
while (!q.empty() && timestamp - q.front() >= 300) {
q.pop();
}
return q.size();
}
private:
queue<int> q;
};
C++:
class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() {}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
v.push_back(timestamp);
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
int i, j;
for (i = 0; i < v.size(); ++i) {
if (v[i] > timestamp - 300) {
break;
}
}
return v.size() - i;
}
private:
vector<int> v;
};
C++:
class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() {
times.resize(300);
hits.resize(300);
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
int idx = timestamp % 300;
if (times[idx] != timestamp) {
times[idx] = timestamp;
hits[idx] = 1;
} else {
++hits[idx];
}
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
int res = 0;
for (int i = 0; i < 300; ++i) {
if (timestamp - times[i] < 300) {
res += hits[i];
}
}
return res;
}
private:
vector<int> times, hits;
};
类似题目:
[LeetCode] 359. Logger Rate Limiter 记录速率限制器
All LeetCode Questions List 题目汇总
[LeetCode] 362. Design Hit Counter 设计点击计数器的更多相关文章
- [LeetCode] Design Hit Counter 设计点击计数器
Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...
- LeetCode 362. Design Hit Counter
原题链接在这里:https://leetcode.com/problems/design-hit-counter/description/ 题目: Design a hit counter which ...
- 【LeetCode】362. Design Hit Counter 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcode ...
- [LC] 362. Design Hit Counter
Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...
- 362. Design Hit Counter
这个傻逼题..我没弄明白 you may assume that calls are being made to the system in chronological order (ie, the ...
- [LeetCode] 641.Design Circular Deque 设计环形双向队列
Design your implementation of the circular double-ended queue (deque). Your implementation should su ...
- [LeetCode] 622.Design Circular Queue 设计环形队列
Design your implementation of the circular queue. The circular queue is a linear data structure in w ...
- LeetCode Design Hit Counter
原题链接在这里:https://leetcode.com/problems/design-hit-counter/. 题目: Design a hit counter which counts the ...
- Design Hit Counter
Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...
随机推荐
- python笔记40-环境迁移freeze生成requirements.txt
前言 我们用python在本地电脑上开发完成一个python自动化项目用例,或者开发完成一个django项目. 需要部署到另外一台电脑或者服务器上的时候,需要导入python相关的依赖包,可以用fre ...
- iptables 规则学习
iptables 一共有 3 张表:mangle,nat,filter mangle 表主要处理 ttl,tos,mark 等信息(进) filter 顾名思义就是过滤器,用作防火墙(出) nat 主 ...
- 开发Electron可能用到的工具
nodejs:搭载谷歌v8内核的高性能的node环境npm:包管理工具webpack:模块打包器jQuery:js必备库Bootstrap:css必备库react:用于构建用户界面的库vue:构建数据 ...
- Centos7 Rsync怎么实现热备份笔记
应用场景:备份Web服务器相关目录下的数据文件,确保指定目录下的所有文件同步. 操作系统:Centos 7 服务器两台:web服务器 172.19.242.70 备份服务器 172.19.242.7 ...
- CSP-J2019游记&解题报告
考前一天晚上失眠.......(其实主要不是因为考试的原因) 很幸运,我们学校就是一个考点,本场作战,应该有一点加持吧. 上午在家复习,看到一篇关于PN532模拟小米手环加密卡的文章,于是,,,,,, ...
- Learning Vector Quantization
学习矢量量化. k近邻的缺点是你需要维持整个数据集的训练. 学习矢量量化算法(简称LVQ)是一种人工神经网络算法,它允许你选择要挂在多少个训练实例上,并精确地了解这些实例应该是什么样子. LVQ的表示 ...
- P4848 崂山白花蛇草水
题意:支持修改的矩形第 \(k\) 大. 题解:动态开点权值线段树 套 Kd-tree. 然后也没什么难的但就是写不对...调了两天才调出来然后发现跑的巨慢,于是又%了一发Claris'题解,跑的真快 ...
- 事件类型(onchange)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 关于windbg报错"No symbols for ntdll. Cannot continue."问题
最近我写个例子程序研究下某个异常情况,故意制造了个崩溃.然后分析dmp文件. 当我执行!address -summary命令想观察下进程当前内存情况时,去报如下错误: 0:000> !addre ...
- CURL shell 使用
#! /bin/bash requrl="http://www.baidu.com/xxxxxx" while true do html=$(curl -s "$requ ...