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;
}
};