单调栈算法题总结

单调栈适用于需要生成指定序列(递增/递减)。

496. 下一个更大元素 I

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // 保存第一个大于指定数值的数
        Map<Integer, Integer> map = new HashMap<>();
        int[] res = new int[nums1.length];
        // 使用一个递减序列的栈,当碰到第一个不符合的序列的数值时,
        // 此数值就是第一个大于栈顶的数。
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < nums2.length; i++) {
            while (stack.size() > 0 && stack.peek() < nums2[i]) {
                int t = stack.pop();
                map.put(t, nums2[i]);
            }
            stack.push(nums2[i]);
        }
        for (int i = 0; i < nums1.length; i++) {
            // 如果map没有保存第一个大于的数,则说明不存在第一个大于它的数。
            // 可能情况:
            // 1. 到达数组末尾
            // 2. 不存在大于它的数
            // 3. 大于它的数在其左边
            res[i] = map.containsKey(nums1[i]) ? map.get(nums1[i]) : -1;
        }
        return res;
    }
}

503. 下一个更大元素 II

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        int[] res = new int[nums.length];
        Arrays.fill(res, -1);
        // 只要遍历两遍数组,就实现了循环。
        for (int i = 0, end = nums.length * 2; i < end; i++) {
            int j = i % nums.length;
            while (stack.size() > 0 && nums[stack.peek()] < nums[j]) {
                int t = stack.pop();
                if (res[t] == -1) {
                    res[t] = nums[j];
                }
            }
            stack.push(j);
        }
        return res;
    }
}
posted @ 2021-08-10 13:15  yghr  阅读(91)  评论(0)    收藏  举报