1. 933最近的请求次数
answer:
stack: push pop;
queue: add,poll;
Queue<Integer> q;
public RecentCounter() {
q = new ArrayDeque<>();
}
public int ping(int t) {
q.add(t);
while (q.peek() < t-3000) {
q.poll();
}
return q.size();
}
2. 225用队列实现栈(还要再刷)
answer:
第一次做!有点意思;
类似的:用栈实现队列;
Queue<Integer> q;
int top = 0;
public MyStack() {
q = new ArrayDeque<>();
}
public void push(int x) {
q.add(x);
top = x;
}
public int pop() {
if (q.isEmpty())
return -1;
int s = q.size();
while (s > 2) {
q.add(q.poll());
s--;
}
top = q.poll();
q.add(top);
return q.poll();
}
public int top() {
return top;
}
public boolean empty() {
if (q.isEmpty())
return true;
return false;
}
3. 232用栈实现队列(还要再刷)
answer:
key:
private Stack<Integer> s1, s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.pop();
}
public int peek() {
if (s2.isEmpty()) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.peek();
}
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
参考:
队列实现栈|栈实现队列