找出数组中每个数右边第一个比它大的元素

题目

找出数组中每个数右边第一个比它大的元素。

思路

  1. 暴力解法

  2. 单调栈
    使用栈结构。从前往后遍历数组每一位时,利用栈更新这一位之前每一位上的数的“右边第一个比它大的元素”。

代码

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;
    }

参考

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

猜你喜欢

转载自www.cnblogs.com/sqqq/p/11716608.html
今日推荐