LeetCode——每日温度

Q:根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

A:单调栈

    public static int[] dailyTemperatures(int[] T) {
        int n = T.length;
        int[] result = new int[n];
        Arrays.fill(result, 0);//初始化
        if (n <= 1)
            return result;
        Stack<Integer> s = new Stack<>();
        s.push(n - 1);
        for (int i = n - 2; i >= 0; i--) {
            while (!s.empty() && T[s.peek()] <= T[i])
                s.pop();//比当前小的都弹出来
            if (!s.empty())
                result[i] = s.peek() - i;
            s.push(i);//当前压入
        }
        return result;
    }

猜你喜欢

转载自www.cnblogs.com/xym4869/p/12619705.html