【代码随想录训练营】【Day58】第十章|单调栈|739.每日温度|496.下一个更大元素 I

每日温度

题目详细:LeetCode.739

详细的题解可查阅:《代码随想录》— 每日温度

Java解法(单调栈):

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        int[] res = new int[temperatures.length];
        for(int i = 0; i < temperatures.length; i++){
            while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
                res[stack.peek()] = i - stack.pop();
            }
            stack.push(i);
        }
        return res;
    }
}

下一个更大元素 I

题目详细:LeetCode.496

详细的题解可查阅:《代码随想录》— 下一个更大元素 I

Java解法(单调栈):

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        // 定义一个哈希表<nums1中的数字,数字的下标>
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], i);
        }
        int[] res = new int[nums1.length];
        Arrays.fill(res, -1);
        Stack<Integer> stack = new Stack<>();
        // 从左往右遍历nums2,保证栈单调递减
        for (int i = 0; i < nums2.length; i++) {
            while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) {
                // 当出现nums2[stack.peek()] < nums2[i]时,说明当前元素nums2[i]是栈内元素的下一个更大元素
                // 将栈内元素出栈
                int pre = nums2[stack.pop()];
                // 判断站内元素是否在nums1中存在,存在则更新其对应下标的值为下一个更大元素nums2[i]
                if (map.containsKey(pre)) {
                    res[map.get(pre)] = nums2[i];
                }
            }
            stack.push(i);
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值