当前位置: 代码迷 >> 综合 >> 739. Daily Temperatures(回看)
  详细解决方案

739. Daily Temperatures(回看)

热度:99   发布时间:2023-11-20 23:30:43.0

在这里插入图片描述
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;}
}