题目:
题解:单调栈
1. 题解一:暴力求解
2. 题解二:单调递减栈
代码:单调栈
1. 代码一:暴力求解
public class code739 {
// 解法1: 暴力求解
public static int[] dailyTemperatures(int[] T) {
int len = T.length;
int res[] = new int[len];
for(int i = 0; i < len; i++)
{
int current = T[i];
if(current < 100)
{
for(int j = i + 1; j < len; j++)
{
if(T[j] > current)
{
res[i] = j - i;
break;
}
}
}
}
return res;
}
public static void main(String[] args) {
int T[] = { 73, 74, 75, 71, 69, 72, 76, 73 };
int res[] = dailyTemperatures(T);
for(int i = 0; i < res.length; i++)
{
System.out.print(res[i] + " ");
}
}
}
2. 代码二:单调递减栈
import java.util.*;
public class code739 {
// 解法2: 单调递减栈
// 找出数组中大于当前元素的第一个元素,到当前元素的距离
// 递减栈,当前元素与栈中元素比较,小则入栈,大则出栈并将二者之间的下标差值为出栈元素的结果值,并继续比较下一个栈顶元素
// 如果栈为空,直接入栈(表示前面元素都找到了比自己大的值)
public static int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int len = T.length;
int res[] = new int[len];
for(int i = 0; i < len; i++)
{
while(!stack.empty() && T[i] > T[stack.peek()])
{
int temp = stack.pop();
res[temp] = i - temp;
}
stack.push(i);
}
return res;
}
public static void main(String[] args) {
int T[] = { 73, 74, 75, 71, 69, 72, 76, 73 };
int res[] = dailyTemperatures(T);
for(int i = 0; i < res.length; i++)
{
System.out.print(res[i] + " ");
}
}
}