代码随想录算法训练营第 47 天 | 739. 每日温度、496. 下一个更大元素 I、503. 下一个更大元素 II

739. 每日温度

题目链接

单调栈

  • 情况一:待判断元素对应的值小于栈顶元素对应的值。将索引压入栈。
  • 情况二:待判断元素对应的值等于栈顶元素对应的值。将索引压入栈。
    (因为题目要求必须找大于某天温度的。)
  • 情况三:待判断元素对应的值大于栈顶元素对应的值。一直弹出栈顶元素直到小于栈顶元素对应的值。同时弹出时记录距离。

最后留在栈中的不用管,因为 result 数组初始化为 0。

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();
        stack.push(0); // 先放入 0

        for (int i = 1; i < n; i++) {
            if (temperatures[i] <= temperatures[stack.peek()]) { // 小于等于栈顶元素,加入栈
                stack.push(i);
            } else { // 大于栈顶元素,一直弹出直到小于栈顶元素。同时弹出时记录距离。
                while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                    result[stack.peek()] = i - stack.peek();
                    stack.pop();
                }
                stack.push(i);
            }
        }

        return result;
    }
}

优化简洁代码:

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                result[stack.peek()] = i - stack.peek();
                stack.pop();
            }
            stack.push(i);
        }

        return result;
    }
}

496. 下一个更大元素 I

题目链接

创建以 nums1.length 为长度的 result 数组。

对 nums1 构建哈希表,记录元素和位置的对应关系。

在 nums2 中运用单调栈,对找到了更大元素的元素,判断如果在哈希表中,就获取哈希表中的索引。将找到的更大元素填入 result 对应的索引中去。

注意:本题找不到是填 -1。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        int[] result = new int[n1];
        Arrays.fill(result, -1); // 题目要求初始化为 -1。

        if (n1 == 0) { // nums1 为空,直接返回空数组。
            return result;
        }

        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n1; i++) {
            map.put(nums1[i], i);
        }

        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n2; i++) {
            while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]) {
                int index = stack.pop();
                if (map.containsKey(nums2[index])) {
                    result[map.get(nums2[index])] = nums2[i]; // 返回的是更大的元素值而不是索引
                }
            }
            stack.push(i);
        }
        
        return result;
    }
}

由于题目要求的是更大的数,而不是索引。所以可以用增强 for 循环:

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        int[] result = new int[n1];
        Arrays.fill(result, -1); // 题目要求初始化为 -1。

        if (n1 == 0) { // nums1 为空,直接返回空数组。
            return result;
        }

        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n1; i++) {
            map.put(nums1[i], i);
        }

        Stack<Integer> stack = new Stack<>();

        for (int x : nums2) {
            while (!stack.isEmpty() && x > stack.peek()) {
                int number = stack.pop();
                if (map.containsKey(number)) {
                    result[map.get(number)] = x; // 返回的是更大的元素值而不是索引
                }
            }
            stack.push(x);
        }
        
        return result;
    }
}

503. 下一个更大元素 II

题目链接

技巧:涉及成环或者首尾相连的题目,都可以通过 取模 的方式。
如 2 倍数组长度遍历数组,但是对数组长度取模。

就是最基本的单调栈模型。
唯一的区别是:

  1. for 循环大小变为 2 * n
  2. 涉及到 i 的地方都对 n 取模

其实也相当于 原来的 for 循环复制一份粘贴在下面。因为一次 for 循环后会剩下点元素留在栈中,第二次 for 循环就可以利用这些元素。

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        Arrays.fill(result, -1);

        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n * 2; i++) { // 大小变为 2 * n
            while (!stack.isEmpty() && nums[i % n] > nums[stack.peek()]) { // 涉及到 i 的地方都对 n 取模
                int index = stack.pop();
                result[index] = nums[i % n];
            }
            stack.push(i % n);
        }

        return result;
    }
}

单调栈总结

单调栈的核心是放索引,而不是具体的值。
(因为直到索引可以去数组中找对应的值;而知道值不能得到索引,且值可能重复。)

单调栈求更大和更小:

  • 如果是求右边第一个大的:从栈顶到栈底递增
  • 如果是求右边第一个小的:从栈顶到栈底递减

单调栈其实有正序遍历和倒序遍历,暂时只掌握正序遍历就可以了。

单调栈模板

  1. while 循环要判断栈非空
  2. while 结束后不要忘记 push
        int n = nums.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n; i++) {
            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) { // 必须判断栈非空
                int index = stack.pop();
                result[index] = i - index;
            }
            stack.push(i); // 别忘了 push
        }

        return result;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值