码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 739. Daily Temperatures

时间:2020-03-15 10:02:10      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:should   you   思路   实现   pop   aar   style   tps   fun   

每日温度。题意是给一个数组,表示每天的气温,请返回一个数组,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。例子,

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].

思路依然是单调栈。单调栈的题目都会以这个tag展示。创建一个stack,遍历数组,依然是把数组的下标放进stack;若当前stack不为空且栈顶元素背后指向的温度小于试图放进去的index背后的温度,则弹出栈顶index,在结果集里面的对应index可以记录i - index,这就是index和他自己之后一个高温天气的时间差。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] dailyTemperatures(int[] T) {
 3         Stack<Integer> stack = new Stack<>();
 4         int[] res = new int[T.length];
 5         for (int i = 0; i < T.length; i++) {
 6             while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
 7                 int index = stack.pop();
 8                 res[index] = i - index;
 9             }
10             stack.push(i);
11         }
12         return res;
13     }
14 }

 

JavaScript实现

 1 /**
 2  * @param {number[]} T
 3  * @return {number[]}
 4  */
 5 var dailyTemperatures = function (T) {
 6     let stack = [];
 7     let res = new Array(T.length).fill(0);
 8     for (let i = 0; i < T.length; i++) {
 9         while (stack.length && T[i] > T[stack[stack.length - 1]]) {
10             let index = stack.pop();
11             res[index] = i - index;
12         }
13         stack.push(i);
14     }
15     return res;
16 };

 

[LeetCode] 739. Daily Temperatures

标签:should   you   思路   实现   pop   aar   style   tps   fun   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12495828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!