求一个数组每个元素右边第一个比它大的元素/单调栈

import java.util.Stack;

import org.junit.Test;

public class solution {
    @Test
    public void testFunc(){
        int[] arr = {13,7,6,12};
        int[] res = get(arr);
        for(int ele:res){
            System.out.print(ele+"  ");
        }
    
    }
    
    public int[] get(int[] arr){
        int[] max=new int[arr.length];
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(0);
        for(int i=1;i<arr.length;i++){
            int top = stack.peek();
            while (!stack.isEmpty() && arr[i]>arr[top]) {
                max[top]=arr[i];
                stack.pop();
                if (!stack.isEmpty()) {
                    top = stack.peek();
                }
            }
            stack.push(i);
        }
        while (!stack.isEmpty()) {
            int top = stack.pop();
            max[top]=-1;
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/wwzheng16/article/details/80999600