思路:
利用一个栈
代码:
自己写的第一版
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
if(pushed.length==0) return true;
Deque<Integer> stack=new ArrayDeque<>();
stack.addLast(pushed[0]);
int i=1,j=0;
while(i<pushed.length||!stack.isEmpty()){
if(j<popped.length&&stack.peekLast()!=null&&stack.peekLast().equals(popped[j])){
stack.removeLast();
j++;
}
else if(i<pushed.length){
stack.addLast(pushed[i++]);
}
else{
return false;
}
}
return true;
}
}
优化后的第二版
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> stack=new ArrayDeque<>();
int j=0;
for(int num:pushed){
stack.addLast(num);
//!stack.isEmpty的判断是放置stack.peekLast()出空指针异常
while(!stack.isEmpty()&&stack.peekLast()==popped[j]){
stack.removeLast();
j++;
}
}
return stack.isEmpty();
}
}
分解:
1)stack.peekLast()==popped[j]不需要使用stack.peekLast().equals(),只要"=="就行,因为stack.peekLast()的是Integer,而popped[j]是int,==可以直接比较值。如果peekLast和removeLast比较,就要用.equals,如果用==,就会比较类型,会返回false
2)第二版中!stack.isEmpty的判断是放置stack.peekLast()出空指针异常,就像第一版中要先判断stack.peekLast()!=null
2)第一版比第二版冗杂多了,第二版代码简化了一点,但时间空间复杂度是一样的
复杂度分析:
时间复杂度:O(N) pushed和popped都要遍历一次,O(2N)
空间复杂度:O(N)额外使用了一个栈,最差情况下要存储N个值