Leetcode每日一题 20240131 Daily Temperatures

文章介绍了如何使用单调栈(MonotonicStack)算法来解决一个关于数组温度的编程问题,即在给定的温度序列中,找到每个温度首次高于其之前温度时的索引差。作者提供了一个Java类`Solution`中的`dailyTemperatures`方法实现。
摘要由CSDN通过智能技术生成

Problems

在一个数组里找到后一个比前一个温度高的index差距, 问题问的是index差距, 所以stack里面不能存温度

Monotonic stacks are a good option when a problem involves comparing the size of numeric elements, with their order being relevant.

stack被用来比较数据大小, 尤其是顺序很相关的时候

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        for (int i = 1; i < n; i++){
        // 注意要考虑stack是不是empty 比较温度大小不一定要用if-else (当可以用while的时候)
            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
                int tmp = stack.pop();
                result[tmp] = i - tmp;
            }
            stack.push(i);
        }
        return result;
    }
}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值