动物收容所
class AnimalShelf {
public Queue<Integer>dog;
public Queue<Integer>cat;
public AnimalShelf() {
dog=new LinkedList<>();
cat=new LinkedList<>();
}
public void enqueue(int[] animal) {
if(animal[1]==0){//猫
cat.add(animal[0]);
}else{//狗
dog.add(animal[0]);
}
}
public int[] dequeueAny() {
if(dog.isEmpty()&&cat.isEmpty()){
return new int[]{-1,-1};
}
if(dog.isEmpty()){
return new int[]{cat.poll(),0};
}
if(cat.isEmpty()){
return new int[]{dog.poll(),1};
}
if(dog.peek()<cat.peek()){
return new int[]{dog.poll(),1};
}
return new int[]{cat.poll(),0};
}
public int[] dequeueDog() {
return dog.isEmpty()?new int[]{-1,-1}:new int[]{dog.poll(),1};
}
public int[] dequeueCat() {
return cat.isEmpty()?new int[]{-1,-1}:new int[]{cat.poll(),0};
}
}
/**
* Your AnimalShelf object will be instantiated and called as such:
* AnimalShelf obj = new AnimalShelf();
* obj.enqueue(animal);
* int[] param_2 = obj.dequeueAny();
* int[] param_3 = obj.dequeueDog();
* int[] param_4 = obj.dequeueCat();
*/
买票需要的时间
class Solution {
public int timeRequiredToBuy(int[] tickets, int k) {
int ans=0;
Queue<Integer>q=new LinkedList<>();
for(int i=0;i<tickets.length;++i){
q.add(i);
}
while(!q.isEmpty()){
if(tickets[k]==0){
break;
}
int index=q.poll();
if(tickets[index]>0){
ans++;
tickets[index]--;
q.add(index);
}
}
return ans;
}
}
最近的请求次数
class RecentCounter {
Queue<Integer>q;
public RecentCounter() {
q=new LinkedList<>();
}
public int ping(int t) {
if(q.isEmpty()||t-3000<=q.peek()){
q.add(t);
return q.size();
}
while(!q.isEmpty()&&t-3000>q.peek()){
q.poll();
}
q.add(t);
return q.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
数据流中的移动平均值
class MovingAverage {
public Queue<Integer>q;
int size;
int sum;
public MovingAverage(int size) {
q=new LinkedList<>();
this.size=size;
sum=0;
}
public double next(int val) {
if(q.size()<size){
sum+=val;
q.add(val);
return sum*1.0/q.size();
}
//q.size()==size
sum-=q.poll();
sum+=val;
q.add(val);
return sum*1.0/size;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/