每日温度

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures

注:leetcode中文题目我差点没看懂,应该是翻译不到位,所以还是尽量看英文吧。。

分析:很容易想到o(n^2)的解法,两个循环搞定。o(n)的方法比较巧妙,相当于记录下的之前的比较结果,节约了时间。
从右往左遍历数组,将大的数的下标保存到栈里,栈最下面的元素最大,最上面的元素离下一个要计算的位置最近。比较当前位置元素与栈顶元素对应的元素的大小,直到找到较大元素或者栈为空,然后计算需要等的天数。

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] res = new int[T.length];
        Stack<Integer> indexStack = new Stack<>();
        for(int i = T.length - 1; i >= 0; --i) {
            while(!indexStack.empty() && T[i] >= T[indexStack.peek()]) indexStack.pop();
            res[i] = indexStack.empty() ? 0 : indexStack.peek() - i;
            indexStack.push(i);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值