【陪伴式刷题】Day 52|单调栈|503.下一个更大元素II(Next Greater Element II)

36 阅读2分钟

刷题顺序以及题解参考卡哥的代码随想录

题目描述

英文版描述

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element innums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

Example 1:

Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2.

Example 2:

Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4]

Constraints:

  • 1 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9

英文版地址

leetcode.com/problems/ne…

中文版描述

给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素

数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。

示例 1:

输入: nums = [1,2,1] 输出: [2,-1,2] 解释: 第一个 1 的下一个更大的数是 2; 数字 2 找不到下一个更大的数; 第二个 1 的下一个最大的数需要循环搜索,结果也是 2。

示例 2:

输入: nums = [1,2,3,4,3] 输出: [2,3,4,-1,4]

提示:

  • 1 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9

中文版地址

leetcode.cn/problems/ne…

解题方法

class Solution {
    public int[] nextGreaterElements(int[] nums) {
       int[] result = new int[nums.length];
        Arrays.fill(result, -1);
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < nums.length * 2; i++) {
            int i1 = i % nums.length;
            if (!stack.isEmpty()) {
                while (!stack.isEmpty() && nums[i1] > nums[stack.peek()]) {
                    Integer pop = stack.pop();
                    result[pop] = nums[i1];
                }
            }
            stack.push(i1);
        }
        return result;
    }
}

复杂度分析

  • 时间复杂度: O(n),其中 n 是序列的长度
  • 空间复杂度: O(n),其中 n 是序列的长度