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 设计点击计数器的更多相关文章

  1. [LeetCode] Design Hit Counter 设计点击计数器

    Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...

  2. LeetCode 362. Design Hit Counter

    原题链接在这里:https://leetcode.com/problems/design-hit-counter/description/ 题目: Design a hit counter which ...

  3. 【LeetCode】362. Design Hit Counter 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcode ...

  4. [LC] 362. Design Hit Counter

    Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...

  5. 362. Design Hit Counter

    这个傻逼题..我没弄明白 you may assume that calls are being made to the system in chronological order (ie, the ...

  6. [LeetCode] 641.Design Circular Deque 设计环形双向队列

    Design your implementation of the circular double-ended queue (deque). Your implementation should su ...

  7. [LeetCode] 622.Design Circular Queue 设计环形队列

    Design your implementation of the circular queue. The circular queue is a linear data structure in w ...

  8. LeetCode Design Hit Counter

    原题链接在这里:https://leetcode.com/problems/design-hit-counter/. 题目: Design a hit counter which counts the ...

  9. Design Hit Counter

    Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...

随机推荐

  1. janusgraph批量导入数据-IBM( janusgraph-utils)的使用

    janusgraph-utils的简介 可与JanusGraph一起使用的实用工具,包括: JanusGraphSchemaImporter:一个groovy脚本,它将图形模式定义(JanusGrap ...

  2. CDN工作机制

    CDN(content delivery network),即内容分布网络,是一种构建在现有Internet上的一种先进的流量分配网络.CDN以缓存网站中的静态数据为主,当用户请求动态内容时,先从CD ...

  3. c++处理字符串string.find()与string::npos

    1. string s  = “xxx”; int a = s.find(‘x’); 如果没有匹配到,那么a = string::npos;

  4. 洛谷 P4316绿豆蛙的归宿

    题目描述 记f[i]表示经过i号点的概率. 那么点v从点u到达的概率=经过点u的概率/点u的出度.由于v可以由多个点走到,所以f[v]+=f[u]/out[u]. 计算f的过程可以在拓扑中完成,同时可 ...

  5. Codeforces & Atcoder神仙题做题记录

    鉴于Codeforces和atcoder上有很多神题,即使发呆了一整节数学课也是肝不出来,所以就记录一下. AGC033B LRUD Game 只要横坐标或者纵坐标超出范围就可以,所以我们只用看其中一 ...

  6. 洛谷P3205 合唱队

    题目 区间dp.但是跟平常的区间dp不同的是,这个题仅仅只是运用了区间dp的通过小区间的信息更新大区间的信息,而没有运用枚举断点的区间dp一般思路. 这个题我们首先发现每个人在插入的时候一定插入到队伍 ...

  7. 洛谷P1560 蜗牛的旅行

    题目 搜索,注意判断特殊情况,并且区分开什么时候转弯什么时候停止.然后转弯的时候更是要注意是否会进入障碍. #include <bits/stdc++.h> using namespace ...

  8. (13)Go接口

    接口(interface)定义了一个对象的行为规范,只定义规范不实现,由具体的对象来实现规范的细节. 接口 接口类型 在Go语言中接口(interface)是一种类型,一种抽象的类型. interfa ...

  9. es6学习2:变量的解构赋值

    一:数组的解构赋值 ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构 let [foo, [[bar], baz]] = [1, [[2], 3]]; foo bar ba ...

  10. QHUOJ - 1533: 计算组合数(大数计算)

    题目描述 给定两个正整数n,m,计算组合数C(n,m).组合数计算公式为:C(n,m)=n!/((n-m)!*m!) 已知n,m <= 50. 结果很大需要使用long long存储. 输入 输 ...