My code:
public class HitCounter {
TreeMap<Integer, Integer> tree;
private int counter = 0;
/** Initialize your data structure here. */
public HitCounter() {
tree = new TreeMap<Integer, Integer>();
tree.put(0, 0);
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
public void hit(int timestamp) {
counter++;
tree.put(timestamp, counter);
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
public int getHits(int timestamp) {
int end = tree.floorKey(timestamp);
int begin = timestamp - 300;
if (begin <= 0) {
return tree.get(end);
}
else {
begin = tree.floorKey(begin);
return tree.get(end) - tree.get(begin);
}
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
自己用 TreeMap 写了出来。
然后研究了下TreeMap
他的 put, get, remove, containsKey, floor 都是 log(n) 时间复杂度。
所以这种实现方法, hit, getHits 的时间复杂度都是 O(log n)
然后看答案看到了一种新的方法:
My code:
public class HitCounter {
Queue<Integer> q = new LinkedList<Integer>();
/** Initialize your data structure here. */
public HitCounter() {
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
public void hit(int timestamp) {
q.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) {
while (!q.isEmpty() && timestamp - q.peek() >= 300) {
q.poll();
}
return q.size();
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/
reference:
https://discuss.leetcode.com/topic/48752/simple-java-solution-with-explanation/2
用一个queue来做。
然后这个方法其实存在一个问题。正如题目中说的,
当hit大量出现的时候,这个方法不能scale
加入 timestamp 1-3000 都 hit
那么, getHits(3001), 就需要先弹出几千个Integer,之后再返回。。。太慢了。
而我的 Treemap 做法,则是 log n 时间内就能算出来,可以scale
Anyway, Good luck, Richardo! — 09/12/2016