题目
分析
本题的意思就是找出按照当前入栈顺序,其所有出栈顺序中字典序最大的出栈序列,
思路:
1、遍历数组,假设此时元素是a[i],将a[i]加入到栈中
2、循环判断判断栈顶元素,是否大于a[i+1]~a[a.length-1]所有的元素,如果是,则将栈顶元素弹出。
3、遍历完数组如果栈非空,则弹出剩余元素。
import java.util.Stack;
public class Solution {
/**
* 栈排序
* @param a int整型一维数组 描述入栈顺序
* @return int整型一维数组
*/
public int[] solve (int[] a) {
// write code here
int[] dp = new int[a.length];
//初始化dp
dp[a.length-1] = -1;
for(int i = a.length-2; i >= 0; i--) {
dp[i] = Math.max(dp[i+1],a[i+1]);
}
int[] res = new int[a.length];
int j = 0;
Stack<Integer> stack = new Stack();
for(int i = 0; i < a.length; i++) {
stack.push(a[i]);
while(!stack.isEmpty() && stack.peek() > dp[i]) {
res[j++] = stack.pop();
}
}
/* 这一步可以不写,这是因为在上面的循环中当遍历到a[a.length-1],栈中的元素一定全都大于dp[a.length-1],这是因为dp[a.length-1] = -1,此时会弹出所有的栈中元素
while(!stack.isEmpty()) {
res[j++] = stack.pop();
}*/
return res;
}
}