[Monotonic stack] 503. Next larger element II

503. The Next Greater Element II

Problem-solving ideas

  • Reference 496. Next Larger Element I

  • First calculate the next element larger than each element of nums2, using a monotonic stack

  • Combine the above result and each element in nums2 to form a mapping map

  • Query the map for each element of Nums1 and record the value of the map

  • But this is the array element of the loop


class Solution {
    
    
    public int[] nextGreaterElements(int[] nums) {
    
    
        // 使用单调栈计算  改造算法   只不过数组元素可以循环
        int n = nums.length;

        // 存放答案的数组
        int[] res = new int[n];
        Stack<Integer> s = new Stack<>();

        for(int i =2 * n - 1; i >= 0; i--){
    
    
            // 判断各自高矮
            while(!s.isEmpty() && s.peek() <= nums[i % n]){
    
    
                s.pop();
            }

            // 存放比当前元素大的元素
            res[i % n] = s.isEmpty()? -1:s.peek();
            s.push(nums[i % n]);
        }

        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/133363436