
解题思路:暴力解法直接遍历一遍,但是最后两个点超时;解决方法用单调栈的方式进行解决,栈存储的是下标,当某一天的温度值比栈顶的温度高的时候,就把栈顶元素弹出,并且在对应answer填入两者下标差值,然后继续对比,直到空栈或者栈顶元素比该天温度高,将该下标存入栈中,然后继续遍历。
暴力解法:
class Solution {public int[] dailyTemperatures(int[] temperatures) {int[] answer = new int[temperatures.length];for(int i=0;i<temperatures.length-1;++i){for(int j=i+1;j<temperatures.length;++j){if(temperatures[j]>temperatures[i]){answer[i] = j-i;break;}}}return answer;}
}
栈解法
class Solution {public int[] dailyTemperatures(int[] temperatures) {Deque<Integer> stack = new LinkedList<Integer>();int[] answer = new int[temperatures.length];for(int i=0;i<temperatures.length;i++){while(!stack.isEmpty()&&temperatures[stack.peek()]<temperatures[i]){answer[stack.peek()] = i-stack.peek();stack.pop();}stack.push(i);}return answer;}
}