LeetCode 739. 每日温度

//暴力法
// class Solution {
//     public int[] dailyTemperatures(int[] T) {
//         //
//         int n = T.length;
//         int [] end = new int[n];

//         for(int i = 0;i < n; i++){
//             int cur = T[i];
//             for(int j = i+1;j<n;j++){
//                 if(T[j] > cur){
//                     end[i] = j-i;
//                     break;
//                 }else{
//                     end[i] = 0;
//                 }
//             }
//         }
//         return end;
//     }
// }
//利用单调栈
class Solution {
    public int[] dailyTemperatures(int[] T) {
        //定义一个结果数组
        int n = T.length ;
        int[] end = new int[n];
        //定义一个栈,存放数组的下标
        Stack<Integer> stack =  new Stack<>();

        for(int i=0;i < n;i++){
            //如果当前的温度 大于 栈顶的 温度
            while(!stack.isEmpty() && T[i] > T[stack.peek()]){
                //end[stack.pop()] = i - stack.peek();//
                int index = stack.pop();
                end[index] = i - index ;
            }
            stack.push(i);
        }
        return end;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/13891524.html