剑指 Offer 31. 栈的压入、弹出序列
作者:互联网
之前写的又不会了。难过。用一个栈来模拟进出序列,最后模拟栈为空,返回true。
算法复杂度
- 时间复杂度: O ( n ) O(n) O(n),虽然有两个循环,但是一个元素最多被操作两次,一次入栈,一次出栈
- 空间复杂度: O ( n ) O(n) O(n),要新建一个堆栈,最坏的情况下,先全部入栈,再全部出栈。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack();
int j = 0;
for(int i : pushed){
stack.push(i);
while(!stack.isEmpty() && popped[j] == stack.peek()){
stack.pop();
j++;
}
}
return stack.isEmpty();
}
}
标签:popped,出栈,压入,Offer,int,31,stack,isEmpty,复杂度 来源: https://blog.csdn.net/zhazha_hui/article/details/113028144