小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
栈的压入、弹出序列
题目
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
来源:力扣(LeetCode)
思路
用pushed中的元素模拟入栈出栈的过程,在压栈的过程中如果栈顶与popped中对应的元素相匹配(用一个i指针记录匹配到的位置),如果满足序列最后stack应该为空
代码
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int i = 0;
for (int num : pushed) {
stack.push(num);
while (!stack.isEmpty() && stack.peek() == popped[i]) {
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}
队列的最大值
题目
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
来源:力扣(LeetCode)
思路
主要需要注意得点是在push_back的过程中,如果max.peekLast()比value小就需要一直弹出,这是因为value会比前面的值晚出队列,然后peekFirst的时候是从队列头开始看的,为了不让前面的比value小的值影响结果,所以把比value小的值弹出。
代码
class MaxQueue {
LinkedList<Integer> keep = new LinkedList<>();
LinkedList<Integer> max = new LinkedList<>();
public MaxQueue() {
}
public int max_value() {
if (max.isEmpty()) return -1;
return max.peekFirst();
}
public void push_back(int value) {
while (!max.isEmpty() && max.peekLast() < value) {
max.pollLast();
}
max.offerLast(value);
keep.offerLast(value);
}
public int pop_front() {
if (keep.isEmpty()) return -1;
int pollFist = keep.pollFirst();
if (max.peekFirst() == pollFist) {
max.pollFirst();
}
return pollFist;
}
}