~~
NC115 栈和排序
~~
描述
给你一个1->n的排列和一个栈,入栈顺序给定
你要在不打乱入栈顺序的情况下,对数组进行从大到小排序
当无法完全排序时,请输出字典序最大的出栈序列
示例1
输入:
[2,1,5,3,4]
返回值:
[5,4,3,1,2]
2入栈;1入栈;5入栈;5出栈;3入栈;4入栈;4出栈;3出栈;1出栈;2出栈
备注:
n<=1e6
import java.util.*;
public class Solution {
/**
* 栈排序
* @param a int整型一维数组 描述入栈顺序
* @return int整型一维数组
*/
public int[] solve (int[] a) {
// write code here
//定义一个栈
Stack<Integer> stack = new Stack<Integer>();
int n = a.length;
int[] res = new int[n];
boolean []vis = new boolean[n+10];
int currenty = 0;
for(int i = 0;i<a.length;i++){
stack.push(a[i]);
vis[a[i]] = true;
while(n>0 && vis[n]){
n--;
}
while(!stack.isEmpty() && n<=stack.peek()){
res[currenty++] = stack.pop();
}
}
while(!stack.isEmpty()){
res[currenty++] = stack.pop();
}
return res;
}
}