LeetCode-503-下一个更大元素Ⅱ

题目描述:
给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 。
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。

题目链接:LeetCode-503-下一个更大元素Ⅱ

解题思路:通过超过下标就取模的思路,其他和 下一个更大元素 一模一样。

代码实现:

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        if (nums == null || nums.length <= 1) return new int[]{-1};
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        int[] res = new int[nums.length];
        Arrays.fill(res, -1);
        for (int i = 1; i < nums.length * 2; i++) {
            // 多余的取模
            // 比较大小
            // nums[stack.peek()] > nums[i]:直接入栈
            // nums[stack.peek()] = nums[i]:直接入栈
            // nums[stack.peek()] < nums[i]:收获结果,
            // i = i % nums.length; 不能这样修改
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i % nums.length]) {
                res[stack.peek()] = nums[i % nums.length];
                stack.pop();
            }
            stack.push(i % nums.length);
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,数据结构)