用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解法一:
- stack1 是入队的
- stack2 是出队的,每次出队完后要保持stack1 的有序性 所以要把stack2的数据放回stack1
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int res = stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return res;
}
}
滑动窗口的最大值
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
解法一:
- 用的是一个优先级队列
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> res = new ArrayList();
if(num.length < size || size <=0 || num == null || num.length == 0){
return res;
}
Queue<Integer> queue = new PriorityQueue<>(((o1, o2) -> o2 - o1));
for(int i = 0;i < size;i++){
queue.add(num[i]);
}
int max = queue.peek();
res.add(max);
for(int i = size;i < num.length ;i++){
queue.remove(num[i - size]);
queue.offer(num[i]);
res.add(queue.peek());
}
return res;
}
}