Bootstrap

力扣 LeetCode 503. 下一个更大元素II(Day25:单调栈)

解题思路:

单调栈找下一个更大的数,并且有环

那么我们可以双倍定义数组大小,并且取模,走后半部分时可以续接上,保证在环内

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int len = nums.length;
        int[] result = new int[nums.length];
        Arrays.fill(result, -1);
        Stack<Integer> stack = new Stack<>();

        stack.push(0);
        for (int i = 1; i < nums.length * 2; i++) {
            if (nums[i % len] <= nums[stack.peek()]) {
                stack.push(i % len);
            } else {
                while (!stack.isEmpty() && nums[i % len] > nums[stack.peek()]) {
                    result[stack.peek()] = nums[i % len];
                    stack.pop();
                }
                stack.push(i % len);
            }
        }
        return result;
    }
}

;