0
点赞
收藏
分享

微信扫一扫

微软坚持Rust语言重写 Windows 11核心

奋斗De奶爸 2023-10-10 阅读 91

题目链接: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;
    }
}
举报

相关推荐

0 条评论