经典算法题:找出数组所有元素右边第一个大于该元素的值

一、题目

给定一个整型数组,数组元素随机无序的,要求打印出所有元素右边第一个大于该元素的值。

二、思路

1)如果栈不为空且元素值A[i]大于栈顶的元素值A[stack.peek()],说明当前元素正好是栈顶元素右边第一个比它大的元素,将栈顶元素弹出。

2)一直循环直到栈顶为空或是当前遍历的元素值小于栈顶元素索引处的值。

3)如果栈为空,说明前面的元素都找到了比它右边大的元素,则直接将当前元素的索引放入栈中

三、实现

public int[] findMaxRightWithStack(int[] array) {
    if (array == null) {
        return array;
    }

    int size = array.length;

    int[] result = new int[size];

    Stack<Integer> stack = new Stack<>();
    stack.push(0);

    int index = 1;

    while (index < size) {
        if (!stack.isEmpty() && array[index] > array[stack.peek()]) {
            result[stack.pop()] = array[index];
        } else {
            stack.push(index);
            index++;
        }
    }

    if (!stack.isEmpty()) {
        result[stack.pop()] = -1;
    }
    
    return result;
}
发布了83 篇原创文章 · 获赞 0 · 访问量 4496

猜你喜欢

转载自blog.csdn.net/zhangdx001/article/details/105578357
今日推荐