首页 > 编程语言 > 详细

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

时间:2019-10-21 22:46:01      阅读:95      评论:0      收藏:0      [点我收藏+]

题目

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

思路

  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

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

原文:https://www.cnblogs.com/sqqq/p/11716608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!