leetcode 739 Daily Temperatures

每日温度

题意:

给定每日温度列表T,请返回一个列表,以便对于输入中的每一天,告诉您要等到温度升高才需要多少天。如果没有将来的可能,请0改写。
例如,给定温度列表T = [73, 74, 75, 71, 69, 72, 76, 73],您的输出应为[1, 1, 4, 2, 1, 1, 0, 0]。

解题思路:

题意理解就是给定一个数组返回数组中的每个数字代表每日的温度请输出当天还需要过几天能够升温 直白理解就是还要经过多少天的温度比当天的温度高。
这道题是单调栈的应用单调栈维持从大到小的次序。
解释单调栈流程
在这里插入图片描述

代码解释

时间复杂度为O(N)
空间复杂度为O(N) 使用了额外的stack来存储数据

 //定义一个Node类型 index为数组的下标 num为数组的值
    public class Node{
        public int index;
        public int num;
        public Node(int index,int num) {
            this.index = index;
            this.num = num;
        }
    }
 /**
     * 单调栈
     * @param T
     * @return
     */
    public int[] dailyTemperaturesStack(int[] T) {
        if (T==null || T.length==0) return T;
        Stack<Node> stack=new Stack<Node>();
        stack.push(new Node(0,T[0])); //定义一个Node类型 index为数组的下标 num为数组的值
        for (int i = 1; i < T.length; i++) {
            //先判断栈是否为空
            while (!stack.isEmpty() && T[i]>stack.peek().num ){  //栈不为空 并且栈顶的元素小于当前将要进入栈中的元素 一直弹出
                Node pop = stack.peek();
                T[pop.index]=i-pop.index;
                stack.pop();
            }
            stack.push(new Node(i,T[i]));  //如果不经过while 说明 栈顶元素大于将要进入栈中的元素 什么也不做
        }
        //这个while是当前数组遍历完了但是栈不为空还有数 为0
        while (!stack.isEmpty()){
            Node pop = stack.pop();
            T[pop.index]=0;
        }
        return T;
    }

升级版:前面的代码主要是为了更快的过用例所以新建了一个Node类
下面栈中直接存储数组的下标

时间复杂度为O(N)
空间复杂度为O(N) 使用了额外的stack来存储数据
/**
     * 优化的单调栈
     * @param T
     * @return
     */
    public int[] dailyTemperatures1(int[] T) {
        if (T==null || T.length==0) return T;
        Stack<Integer> stack=new Stack<>();
        for (int i = 0; i < T.length; i++) {
            while (!stack.isEmpty() && T[i]>T[stack.peek()]){
                Integer peek = stack.peek();
                T[peek]=i-peek;
                stack.pop();
            }
            stack.push(i);
        }
        while (!stack.isEmpty()){
            Integer pop = stack.pop();
            T[pop]=0;
        }
        return T;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值