LeetCode——739. 每日温度(栈)

739. 每日温度(栈)

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/daily-temperatures
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目**

请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

1、遍历**

思想**

双层循环遍历温度数组,第一层遍历当前结点i,第二层遍历i之后的结点,找到第一个大于结点i的温度,然后记录两者之间差值;注意当后面温度都不会升高这一特殊情况的处理

代码**

/*

*/

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int len = T.length;
        int[] days = new int[len];
        for(int i = 0; i < len - 1; i++){
            int cnt = 1;
            int flag = 0;
            for(int j = i + 1; j < len; j++){
                // if(T[j] <= T[i]){//未找到
                //     cnt++;
                // }
                // else{
                //     flag = 1;
                //     days[i] = cnt;
                //     break;
                // }
                if(T[j] > T[i]){
                    flag = 1;
                    days[i] = j - i;
                    break;
                }
            }
            if(flag == 0){
                days[i] = 0;
            }
        }
        return days;
    }
}

2、单调栈**

思想**

从前往后遍历温度数组,如果栈为空,直接将当前下标对应温度入栈;如果栈不为空,则比较当前下标温度与栈顶下标温度,如果大于栈顶,则弹出栈顶元素,更新栈顶下标对应的days数组值;否则入栈

代码**


class Solution {
    public int[] dailyTemperatures(int[] T) {
        int len = T.length;
        int[] days= new int[len];
        Stack<Integer> stack = new Stack<Integer>();
        for(int i = 0; i < len; i++){
            while(!stack.isEmpty() && T[i] > T[stack.peek()]){//注意用while而不用if,因为可能一次弹出多个元素;当前下标温度大于栈顶下标温度
                int index = stack.pop();
                days[index] = i - index;
            }
            stack.push(i);
        }
        return days;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34767784/article/details/107352655