The right of each array to find a large number of elements than it

topic

Find out the right of each array is larger than the number of the first of its elements.

Thinking

  1. Violence Solution

  2. Monotone stack
    using the stack structure. When every front to back through the array, using the stack to update a "right of the first element is larger than its" number on every one before this one.

Code

public static int[] findMaxRightWithStack(int[] array) {
        if(array == null) return null;
        int n = array.length;
        int[] ret = new int[n];
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        int i = 1;
        while(i < n) {
            if(!stack.isEmpty() && array[i] > array[stack.peek()])
                ret[stack.pop()] = array[i];
            else
                stack.push(i++);
        }
        while(!stack.isEmpty())
            ret[stack.pop()] = -1;

        return ret;
    }

reference

https://blog.csdn.net/smileiam/article/details/88732245

Guess you like

Origin www.cnblogs.com/sqqq/p/11716608.html