LeetCode one question per day (2021-3-6, the next bigger element II)

LeetCode one question per day (2021-3-6, the next bigger element II)

Title description

Given a looping array (the next element of the last element is the first element of the array), output the next larger element of each element. The next larger element of the number x is in the traversal order of the array. The first number after this number is larger than it, which means you should search for the next larger number in a loop. If it does not exist, -1 is output.
Insert picture description here
  I originally thought that this month was the month of dynamic planning, but I found that the official should be thinking of more questions about array-related skills. This time I used a monotonic stack. The reason it is called a monotonic stack is that the elements in this stack are monotonically increasing/decreasing. The monotonic stack is very easy to use to deal with the problem of finding the next larger/smaller value (a small tip: when building a stack in Java, the official recommendation is to use the data structure Deque instead of Stack. For specific reasons, please refer to the article Java programmers , Don't use Stack?! ).

  The idea of ​​solving the problem is actually not complicated. Every time a new nums[i] is traversed, all the elements smaller than it are popped from the stack, and the next larger element of these elements is nums[i], and then the position i is entered Stack. But there is another problem here, the topic is looping the array, so if you only traverse it once, you may not be able to find the answer for the element after the subscript (its next larger element is likely to be in the first half of the array), so it is traversed twice .

class Solution {
    
    
    public int[] nextGreaterElements(int[] nums) {
    
    
        int n = nums.length;
        int[] ans = new int[n];
        //数组中一定有元素不存在比它更大的数,预先将值设为-1
        Arrays.fill(ans, -1);
        //构建单调栈,每遍历一个新的nums[i],就弹出栈中所有小于它的元素,且其下一个更大元素即为nums[i]
        Deque<Integer> stack = new ArrayDeque<>();
        //循环数组,遍历两次一定能全部结束
        for(int i = 0; i < 2 * n; i++){
    
    
            while(!stack.isEmpty() && nums[stack.peek()] < nums[i % n]){
    
    
                ans[stack.pop()] = nums[i % n];
            }
            stack.push(i % n);
        }
        return ans;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/GGG_Yu/article/details/114436995