Leetcode - Design Hit Counter

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,324评论 19 139
  • 在尝试了若干次友谊手链后,我终于鼓起勇气开始了新的尝试。 这是我编的第一条,很明显,错误百出。 接下来是复杂款的8...
    卡波阅读 2,875评论 0 1
  • (一) 梦里我写诗 是天下第一好的诗 想象力,有阳光和青草 诗人 有他该有的 两边都是法国梧桐的思南路 骑着旧单车...
    山人阅读 1,066评论 0 3