问题描述:给出一组数,找出数组中每个数的右边第一个比它大的数
问题分析:利用单调栈,从左至右依次压入数据的索引(若直接压数,则还需要一个数组保存栈中元素所对应的数组位置,如果当前元素小于等于栈顶的索引所对应的数组的值,入栈当前索引,否则将栈顶索引出栈,并在栈顶索引所对应的res数组中记录下当前的值。到最后再检查栈中剩余元素,代表剩余元素右边没有比它大的值,在res对应位置赋值为-1。
代码:
import java.util.Stack;
public class FindFirstBiggerNum {
public static void main(String[] arg) {
int array[]=new int[] {1,5,3,6,4,8,9,10};
int res[]=findMax(array);
for(int num:res) {
System.out.println(num);
}
}
public static int[] findMax(int[] array) {
int len =array.length;
Stack<Integer> st = new Stack<Integer>();
int res[]=new int[len];
int i=0;
while(i<len) {
if(st.isEmpty()||array[i]<=array[st.peek()]) {
st.push(i);
i++;
}else {
res[st.pop()]=array[i];
}
}
while(!st.isEmpty()) {
res[st.pop()]=-1;
}
return res;
}
}