n2的方法(超时)
class Solution {
public int[] dailyTemperatures(int[] T) {
//Stack<Integer> stack1 = new Stack<>();
//Stack<Integer> stack2 = new Stack<>();
int n = T.length;//数组的长度
int [] res = new int[n];
int tmp = 0;
boolean flag = false;
for(int i = 0 ;i < n ;i++)
{
for(int j = n-1;j>i;j--)
{
if(T[j]>T[i])
{
tmp = j-i;
flag = true;
}
}
if(flag) res[i] = tmp;
else res[i] = 0;
flag = false;
}
return res;
}
}
官方题解:
用栈的方法
class Solution {
public int[] dailyTemperatures(int[] T) {
int[] ans = new int[T.length];
Stack<Integer> stack = new Stack();
for (int i = T.length - 1; i >= 0; --i) {
while (!stack.isEmpty() && T[i] >= T[stack.peek()]) stack.pop();
ans[i] = stack.isEmpty() ? 0 : stack.peek() - i;
stack.push(i);
}
return ans;
}
}