【题目】

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

还有几天会升温。

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

【思路】

暴力求解,用时太长了……参考答案用stack

【代码】

堆栈,倒序比较,当

1、stack不为空,T[i-1]>T[i],证明不会升温,pop出栈跳出。进行步骤2

2、判断stack是否为空,空栈无条件满足返回0,否则【顶点(升温点)-循环数i 】为天数

3、把i压入栈。

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;
    }
}

 

方便理解

 

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int tmp[]=new int[T.length];
        Arrays.fill(tmp, 1);
        tmp[T.length-1]=0;
        for(int i=0;i<T.length-1;i++){
            int j=i+1;
            while(T[j]<=T[i]){
                    ++j;
                    tmp[i]++;
                if(j>=T.length){
                    break;
                }
            }
            tmp[i]=j<T.length?tmp[i]:0;
        }
        return tmp;
    }
}

 

 posted on 2018-11-11 17:38  alau  阅读(135)  评论(0编辑  收藏  举报