import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @return int整型一维数组
     */
    public int[] nextGreaterElement(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        Arrays.fill(result, -1);

        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
                int index = stack.pop();
                result[index] = nums[i];
            }
            stack.push(i);
        }

        return result;
    }
}

本题知识点分析:

1.栈的出栈和入栈

2.数学模拟

3.数组遍历

本题解题思路分析:

1.栈用于存放元素的索引

2.先利用API函数,将所有result数组中值设为-1,后面没被赋值的就说明,当前数字找不到比它更大的下一个数字

3.如果栈不为空并且当前遍历的元素大于栈顶元素,那么就Pop索引,然后将该索引位置的result数组赋值为当前元素,用while进行循环

本题使用编程语言: Java