LintCode 215: Rate Limiter (System Design 题)

该博客介绍主要数据结构采用了map,map是信息技术领域常用的数据结构,能高效存储和检索数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要数据结构采用map

class Solution {
public:
    /*
     * @param timestamp: the current timestamp
     * @param event: the string to distinct different event
     * @param rate: the format is [integer]/[s/m/h/d]
     * @param increment: whether we should increase the counter
     * @return: true or false to indicate the event is limited or not
     */

    bool isRatelimited(int timestamp, string event, string rate, bool increment) {
        int timeScale = 0;
        int pos = rate.find('/');
        int quota;
        stringstream ss;
        ss << rate.substr(0, pos); //pos also shows # of chars from 0 to pos
        ss >> quota; 
        string timeType = rate.substr(pos + 1, 1);
        switch (timeType[0]) {
            case 's':
                timeScale = 1;
                break;
            case 'm':
                timeScale = 60;
                break;
            case 'h':
                timeScale = 3600;
                break;
            case 'd':
                timeScale = 86400;
                break;
            default: 
                break;
        }

        int start_time = timestamp - timeScale + 1;
        int counter = 0;
        for (auto it = hashmap[event].lower_bound(start_time); it != hashmap[event].end(); ++it) {
                if (it->first < start_time) break;
                counter += it->second;
            }

        //we can only increment the count if increment is true
        if ((counter < quota) && increment) {  
            if (hashmap.find(event) == hashmap.end()) {
                hashmap[event] = map<int, int>();
            } else {
                if (hashmap[event].find(timestamp) == hashmap[event].end()) {
                    hashmap[event][timestamp] = 1;
                } else {
                    hashmap[event][timestamp]++;
                }
            }    
        }    

        return counter >= quota;   
    }

private:
    map<string, map<int, int>> hashmap;   //event, timestamp, count

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值