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

本文介绍了两个LeetCode题目,分别是基于栈的每日温度数组问题,通过deque操作找到每个温度出现后满足条件的后续温度;以及使用哈希映射和双端队列解决下一个更大元素I问题,找到给定数组nums1中每个元素在nums2中的第一个大于它的元素的索引。
摘要由CSDN通过智能技术生成

739. 每日温度

题目链接:739. 每日温度 - 力扣(LeetCode)

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int len = temperatures.length;
        int[] ans = new int[len];
        Deque<Integer> dq = new ArrayDeque<Integer>();
        for(int i = 0; i < len; ++i) {
            if(dq.isEmpty()) {
                dq.addLast(i);
            }else {
                while(!dq.isEmpty() && temperatures[dq.getLast()] < temperatures[i]) {
                    int a = dq.pollLast();
                    ans[a] = i - a;
                }
                dq.addLast(i);
            }
        }
        return ans;
    }
}

496.下一个更大元素 I

题目链接:496. 下一个更大元素 I - 力扣(LeetCode)

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        HashMap<Integer,Integer> map = new HashMap<>();
        int[] ans = new int[nums1.length];
        Deque<Integer> dq = new ArrayDeque<>();
        for(int i = 0; i < nums1.length; ++i) {
            map.put(nums1[i], i);
            ans[i] = -1;
        }
        for(int i : nums2) {
            if(dq.isEmpty()) {
                dq.addLast(i);
            }else {
                while(!dq.isEmpty() && i > dq.peekLast()) {
                    int a = dq.pollLast();
                    if(map.containsKey(a)) {
                        ans[map.get(a)] = i;
                    }
                }
                dq.offerLast(i);
            }
        }
        return ans;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值