class MovingAverage {
public:
/** Initialize your data structure here. */
queue<int>q;
int max_size;
int now_size;
int sum;
MovingAverage(int size) {
max_size = size;
sum = 0;
now_size = 0;
}
double next(int val) {
if(q.empty()){
q.push(val);
sum += val;
now_size++;
}
else{
if(q.size()<max_size){
q.push(val);
sum += val;
now_size++;
}
else{
sum -= q.front();
q.pop();
q.push(val);
sum += val;
}
}
double ans = sum * 1.0 / now_size;
return ans;
}
};
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage* obj = new MovingAverage(size);
* double param_1 = obj->next(val);
*/
class RecentCounter {
public:
queue<int>q;
RecentCounter() {
}
int ping(int t) {
q.push(t);
int f=t-3000;
while(q.front()<f) q.pop();
return q.size();
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/
剑指 Offer II 043. 往完全二叉树添加节点
初始化队列操作,这样每一次的其他操作都是O(1)
class CBTInserter {
public:
TreeNode* head = NULL;
queue<TreeNode*>q;
CBTInserter(TreeNode* root) {
head = root;
q.push(root);
while(!q.empty()){
int len = q.size();
for(int i = 0; i < len; i++){
auto r = q.front();
if(r->left) q.push(r->left);
if(!r->left||!r->right) return ;
q.pop();
q.push(r->right);
}
}
}
int insert(int v) {
auto r = q.front();
if(r->left){
r->right = new TreeNode(v);
q.pop();
q.push(r->right);
}
else{
r->left = new TreeNode(v);
q.push(r->left);
}
return r->val;
}
TreeNode* get_root() {
return head;
}
};