力扣训练6

文章介绍了三个编程问题的解决方案:RecentCounter类实现最近请求计数,使用队列处理时间窗口;Pow函数利用递归计算x的n次幂,特别处理了0,1,-1的情况;设计MyCircularQueue类,用数组模拟循环队列,支持入队、出队等操作。
摘要由CSDN通过智能技术生成
933. 最近的请求次数d

队列思想

class RecentCounter {
public:
    RecentCounter() {

    }
    
    int ping(int t) {
        q_.push(t);
        while ((t - q_.front()) > 3000) {
            q_.pop();
        }
        return q_.size();
    }
    queue<int> q_;
};

50. Pow(x, n)

使用递归求解,每次计算x^(n/2),并乘上额外的值。
对3个较为特殊的的取值,即0, 1, -1进行额外判断。

class Solution {
public:
    unordered_map<int, double> record;

    double _myPow(double x, int n) {
        if (record.count(n)) {
            return record[n];
        }
    
        int half = n >> 1;
        double temp1 = myPow(x, half);
        return temp1 * temp1 * record[n-half-half];
    }

    double myPow(double x, int n) {
     
        record = {{0, 1}, {1, x}, {-1, 1/x}};
        return _myPow(x, n);
    }
};

622. 设计循环队列

使用数组模拟

class MyCircularQueue {
public:
    vector<int>v;
    int first=0; //头
    int end=-1; //尾
    int num=0;//队列中元素个数
    int size=0;//队列最大容量
    MyCircularQueue(int k) {
        v.resize(k,0);
        size=k;
    }
    
    bool enQueue(int value) {
        if(num==size) return false;
        end=(end+1)%size;
        v[end]=value;
        ++num;
        return true;
    }
    
    bool deQueue() {
        //判断队列是否为空,空 返回false
        if(num==0) return false;
        first=(first+1)%size;
        --num;
        return true;
    }
    
    int Front() {
        if(num==0) return -1;
        return v[first];
    }
    
    int Rear() {
        if(num==0) return -1;
        return v[end];
    }
    
    bool isEmpty() {
        if(num==0) return true;
        return false;
    }
    
    bool isFull() {
        if(num==size) return true;
        return false;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值