LeeCode739每日温度(Java)(单调栈)

题目链接:LeeCode739每日温度
题目描述:在这里插入图片描述
单调栈,先将温度下标压到栈里面,有比该温度大的温度时将数据弹出栈,记录相差天数

public static int[] dailyTemperatures(int[] T) {
    
    
        Stack<Integer> stack=new Stack<>();
        int[] ans=new int[T.length];
        for (int i = 0; i < T.length; i++) {
    
    
        	//当栈中有元素且当前数大于栈顶,将栈顶弹出并记录相差天数
            while(!stack.isEmpty()&&T[i]>T[stack.peek()]){
    
    
                Integer pop = stack.pop();
                ans[pop]=i-pop;
            }
            stack.push(i);
        }
        //当所有数据算完还有剩余元素,即后续没有比该元素大的元素,置0
        while (!stack.isEmpty()) {
    
    
            ans[stack.pop()]=0;
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/weixin_43590593/article/details/114604584