一、题目描述

来源:https://leetcode-cn.com/problems/daily-temperatures/

二、思路

原则:第i天的温度可以用来判断前面哪天温度比它低。使用数据结构:栈。出栈和入栈的条件如下:

  • 出栈条件:栈顶温度temperatures[t]比第i天的温度temperatures[i]低,因此,第t天后,再等i-t天会有更高温度,将temperatures[t]出栈;
    持续出栈,直到temperatures[t]temperatures[i]高,或者栈为空。
  • 入栈条件:根据结束出栈操作的原则,进行完出栈操作后,栈顶温度temperatures[t]temperatures[i]高,或者栈为空,因此直接将temperatures[i]入栈即可。
    根据上述出栈和入栈条件,保存在栈中的温度是肯定是有序的,从栈底到栈顶温度依次降低(因为如果遇到更高的温度,低温就会出栈)。

三、代码(Java)

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] result = new int[n];

        Stack<Integer> tpchStk = new Stack<Integer>();  //思路中描述的栈
        Stack<Integer> indexStk = new Stack<Integer>();  //这个栈用来维护下标信息,用来计算天数差

        for(int i = 0; i < n; i++){
            while(!tpchStk.empty() && tpchStk.peek() < temperatures[i]){
                tpchStk.pop();
                result[indexStk.peek()] = i-indexStk.pop();
            }

            tpchStk.push(temperatures[i]);
            indexStk.push(i);
        }
        return result;
    }
}
posted on 2021-10-21 10:15  滔特特  阅读(43)  评论(0编辑  收藏  举报