##題目描述 輸入兩個整數序列,第一個序串列示堆疊的壓入順序,請判斷第二個序列是否可能為該堆疊的彈出順序,假設壓入堆疊的所有數字均不相等,例如序列1,2,3,4,5是某堆疊的壓入順序,序列4,5,3,2,1是該壓堆疊序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓堆疊序列的彈出序列,(注意:這兩個序列的長度是相等的)
思路
新建一個堆疊,將陣列A壓入堆疊中,當堆疊頂元素等于陣列B時,就將其出堆疊,當回圈結束時,判斷堆疊是否為空,若為空則回傳true.
時間復雜度O(n),空間復雜度O(n),
代碼
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length == 0 && popA.length != 0) return false;
Stack<Integer> stack = new Stack<Integer>();
int j = 0;
for(int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while(!stack.empty() && stack.peek() == popA[j]) {
stack.pop();
j++;
}
}
return stack.empty();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/85161.html
標籤:其他
上一篇:[LeetCode] 143. Reorder List
下一篇:從上往下列印二叉樹
