LeetCode Daily Temperatures

Given a list of daily temperatures, produce a list 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 temperatures = [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].

 

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

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

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

 

题解:这题是可以和LeetCode中的栈一类题中的nextGreaterElement I这道题类似,基本是一样的。都是通过一个Stack+hashMap来实现,其中stack放的是原来数组元素,然后逐渐遍历,当发现数组中第一个比之前的其他元素都要大的元素后,就将当前栈的栈顶元素压出栈,然后将key作为当前数组中即温度,将value作为第一个比当前温度高的温度的下标,用于后续计算两个下标之间的差值。

public int[] dailyTemperatures(int[] temperatures) 
{
        int n = temperatures.length;
        int[] ans = new int[n];

        Stack<Integer> stack = new Stack<>();
        Map<Integer, Integer> mem = new HashMap<>();
        for (int i = 0; i < n; ++i)    //用于扫描温度数组
        {
            while (!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) 
            {         //栈用来保存还没有找到比该温度大的温度,当找到栈顶温度比该温度要大时,就 
                      //将该元素压出栈,同时将该温度及第一个比该温度要大的位置保存在HashMap中
                int nxt = stack.pop();
                mem.put(nxt, i);
            }
            stack.push(i);
        }

        for (int i = 0; i < n; ++i)  //最后再次遍历一遍,寻找保存在hashMap中的元素,如果存在 
                                     //某个Key,那么意味着存在比该key要大的元素,那么直接计算 
                                     //相关的差即可。
        {
            if (mem.containsKey(i)) 
            {
                ans[i] = mem.get(i) - i;
            }
            else ans[i] = 0;
        }

        return ans;
    }

这道题与后面的nextGreaterElement I雷同,都是一个思路,且相同的做法。一模一样,这两题都可以一起来进行对比。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值