Day 58|739. 每日温度| 496.下一个更大元素

这两段代码分别展示了如何利用栈数据结构解决两个数组相关问题:1)计算每日温度中比当前日更高温度的天数;2)查找数组中的下一个更大元素。第一段代码中,栈用于存储温度数组的索引,以便回溯计算等待升高天数。第二段代码中,栈用于跟踪遍历第二个数组时遇到的更大元素,同时使用HashMap快速访问第一个数组的索引,以填充结果数组。
摘要由CSDN通过智能技术生成

● 739. 每日温度

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

● 496.下一个更大元素 I

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
    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];
    Stack<Integer> stack = new Stack<>();
    Arrays.fill(res,-1);
​
    for(int i = 0;i<nums2.length;i++){
        while(!stack.isEmpty() && nums2[stack.peek()] < nums2[i]){
            int pre = nums2[stack.pop()];
            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、付费专栏及课程。

余额充值