单调栈结构(进阶) + 栈的使用 + 思维
单调栈结构(进阶)
单调栈结构(进阶)
题目描述
方法一:暴力法
@Test
public void main1(){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] nums = new int[n];
for(int i=0; i<n; i++){
nums[i] = cin.nextInt();
}
int mins = 1000006;
int mini = -1;
int[] min = new int[n];
int[] max = new int[n];
for(int i=0; i<n; i++){
int j;
for(j=i-1; j>=0; j--){
if(nums[j] < nums[i]){
min[i] = j;
break;
}
}
if(j == -1)
min[i] = -1;
for(j=i+1; j<n; j++){
if(nums[j] < nums[i]){
max[i] = j;
break;
}
}
if(j == n)
max[i] = -1;
}
for(int i=0; i<n; i++){
System.out.println(min[i] + " " + max[i]);
}
}
方法二:使用单调递增栈维护单向的最小值
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] nums = new int[n];
for(int i=0; i<n; i++){
nums[i] = cin.nextInt();
}
Stack<Integer> sta = new Stack<>();//严格递增栈,存储序号
int[] mins = new int[n];
int[] maxs = new int[n];
for(int i=0; i<n; i++){
while(!sta.isEmpty() && nums[sta.peek()] >= nums[i]){
sta.pop();
}
if(!sta.isEmpty()){
mins[i] = sta.peek();
}else mins[i] = -1;
sta.push(i);
}
sta.clear();
for(int i=n-1; i>=0; i--){
while(!sta.isEmpty() && nums[sta.peek()] >= nums[i]){
sta.pop();
}
if(!sta.isEmpty()){
maxs[i] = sta.peek();
}else maxs[i] = -1;
sta.push(i);
}
for(int i=0; i<n; i++){
System.out.println(mins[i] + " " + maxs[i]);
}
}
Either Excellent or Rusty