LintCode-505: Web Logger (System Design题)

数据结构采用deque,参考了网上的答案。
注意
1) get_hit_count_in_last_5_minute()里面必须用<=。
2) 同一个timestamp可能hit多次,所以都必须加起来。
3)deque.front()是最老的entry,所以将其与当前timestamp比较,若不在当前5分钟内,则其count不算,再pop_front(),继续与当前timestamp比较。

class Node {
public:
    Node(int t, int c) : timestamp(t), count(c) {}
    int32_t getTimestamp() {return timestamp;}
    void incCount() {count++;}
    uint32_t getCount() {return count;}
private:
    int32_t timestamp;
    uint32_t count;
};

class WebLogger {
public:
    WebLogger() : count(0) {}

    /*
     * @param timestamp: An integer
     * @return: nothing
     */
    void hit(int timestamp) {
        if (!dq.empty() && (dq.front().getTimestamp() == timestamp)) {
            dq.front().incCount();
        } else {
            dq.push_back(Node(timestamp, 1));
        }
        count++;
    }

    /*
     * @param timestamp: An integer
     * @return: An integer
     */
    int get_hit_count_in_last_5_minutes(int timestamp) {
        while(!dq.empty() && ((dq.front().getTimestamp() + 300) <= timestamp)) {
            count -= dq.front().getCount();
            dq.pop_front();
        }
        return count;
    }

private:
    uint32_t count;
    deque<Node> dq;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值