每日温度

题目

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

解法

暴力

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int[] dailyTemperatures(int[] T) {
if(T == null) return new int[0];
int len = T.length;
int[] res = new int[len];

boolean flag = false;
for(int i=0; i<len; i++) {
for(int j=i+1; j<len; j++) {
if(T[j] > T[i]) {

flag = true;
res[i] = j-i;
break;
}
}
if (flag == false) {
res[i] = 0;
} else {
flag = false;
}
}
return res
}
}

对应的元素 后进先出 单调栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int[] dailyTemperatures(int[] T) {
if(T == null) return new int[0];
int len = T.length;
int[] res = new int[len];
Deque<Integer> stack = new LinkedList<>();
for(int i=0; i<len; i++) {
int temperature = T[i];
while(!stack.isEmpty() && temperature > T[stack.peek()]){
int preIndex = stack.pop();
res[preIndex] = i-preIndex;
}

stack.push(i);
}
return res;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×